Como explicar para alguém sóbrio que o código abaixo não funciona?
final String name = "Sergio Oliveira Jr.";
if (name.matches("Oliveira")) {
System.out.println("The regular expression 'Oliveira' matches the string 'Sergio Oliveira Jr.'");
} else {
System.out.println("Sorry!");
}
O cara que escreveu o método matches(String regex) da classe String não sabia que para você matchear a string inteira você deve usar a regex: “^Oliveira$”. Em todas as outras linguagens, a regex “Oliveira” significa faca o match em qualquer lugar da String. Menos em Java.
Para quem já programou em uma linguagem com suporte descente a regular expressions, vai gostar muito de conhecer o MentaRegex: http://mentaregex.soliveirajr.com/
Alguém mais ficava irritado com o suporte tosco do Java a regular expressions???
Veja como vc pode fazer com o MentaRegex:
:arrow: The method matches returns a boolean saying whether we have a regex match or not.
matches("Sergio Oliveira Jr.", "/oliveira/i" ) => true
:arrow: The method match returns an array with the groups matched. So it not only tells you whether you have a match or not but it also returns the groups matched in case you have a match.
match("aa11bb22", "/(\\d+)/g" ) => ["11", "22"]
:arrow: The method sub allows you perform substitutions with regex.
sub("aa11bb22", "s/\\d+/00/g" ) => "aa00bb00"
:arrow: Support global and case-insensitive regex.
match("aa11bb22", "/(\\d+)/" ) => ["11"]
match("aa11bb22", "/(\\d+)/g" ) => ["11", "22"]
matches("Sergio Oliveira Jr.", "/oliveira/" ) => false
matches("Sergio Oliveira Jr.", "/oliveira/i" ) => true
:arrow: Allows you to change the escape character in case you don’t like to see so many ‘’.
match("aa11bb22", "/(\\d+)/g" ) => ["11", "22"]
match("aa11bb22", "/(#d+)/g", '#' ) => ["11", "22"]