I have strings with parentheses and also escaped characters. I need to match against these characters and also delete them. In the following code, I use matches() and replaceAll() with the same regex, but the matches() returns false, while the replaceAll() seems to match just fine, because the replaceAll() executes and removes the characters. Can someone explain?
String input = "(aaaa)\\b";
boolean matchResult = input.matches("\\(|\\)|\\\\[a-z]+");
System.out.printf("matchResult=%s\n", matchResult);
String output = input.replaceAll("\\(|\\)|\\\\[a-z]+", "");
System.out.printf("INPUT: %s --> OUTPUT: %s\n", input, output);
Prints out:
matchResult=false
INPUT: (aaaa) --> OUTPUT: aaaa
What
matchesis doing has already been explained by Binyamin Sharet. I want to extend this a bit.Java does not have a “findall” or a “g” modifier like other languages have it to get all matches at once.
The Java
Matcherclass knows only two methods to use a pattern against a string (without replacing it)matches(): matches the whole string against the patternfind(): returns the next matchIf you want to get all things that fits your pattern, you need to use
find()in a loop, something like this:or if you are only interested if your pattern exists in the string