2

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

Community
  • 1
  • 1
Cloverr
  • 208
  • 3
  • 12
  • 2
    You're using the same matcher twice. If you take out the `matches()` check, then the `find()` check will work. – khelwood Aug 15 '16 at 10:02
  • try swapping `find` and `matches` and observe what happens ;) – SomeJavaGuy Aug 15 '16 at 10:02
  • 1
    @Blobonat I read that question and its mentioned in a link too in the question.. – Cloverr Aug 15 '16 at 10:05
  • 1
    @Cloverr `matches()` matches the entire reagion, `find()` tries to matches the next region. when `matches()` is called the next region is already at the end of the String, so `find()` doesn´t have a region to match up against anymore. As a result you get `false`. – SomeJavaGuy Aug 15 '16 at 10:08

1 Answers1

4

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());
fabian
  • 80,457
  • 12
  • 86
  • 114
  • 1
    from [this Question](http://stackoverflow.com/questions/11391337/java-pattern-matcher-create-new-or-reset) it should be better to reuse the matcher instead of creating a new one. – SomeJavaGuy Aug 15 '16 at 10:09
  • If I call matches() twice, the second one would start again from beginning or after where the previous matches() ended? – Cloverr Aug 15 '16 at 10:16
  • 1
    @Cloverr from the beginning. `matches` always checks from the start of the region, which is the whole string by default. – fabian Aug 15 '16 at 10:26