Cloverr Cloverr - 3 months ago 9
Java Question

Java regex, matches and find

I am still having problems understanding difference in matches() and find(), here the code

final Matcher subMatcher = Pattern.compile("\\d+").matcher("123");
System.out.println("Found : " + subMatcher.matches());
System.out.println("Found : " + subMatcher.find());


Output is

Found : true
Found : false


Of what I understand about matches and find from this answer, is that matches() tries to match the whole string while find() only tries to match the next matching substring, and the matcher adds a ^ and $ meta-character to start and beginning and the find() can have different results if we use it multiple no of times, but here still 123 remains a substring, and the second output should be true. If i comment out the second line then it does shows output as true

Answer

When you call matches(), the Matcher already searches for a match (the whole String). Calling find the Matcher will try to find the pattern again after the current match, but since there are no characters left after a match that matches the entire String, find returns false.

To search theString again, you'd need to create a new Matcher or call reset():

final Matcher subMatcher = Pattern.compile("\\d+").matcher("123");
System.out.println("Found : " + subMatcher.matches());
subMatcher.reset();
System.out.println("Found : " + subMatcher.find());