I’ve noticed that calling Matcher.lookingAt() affects Matcher.find(). I ran lookingAt() in my code and it returned true. When I then ran find() so that I can start returning matches, i got false. If I remove the lookingAt() call, find() returns true and prints my matches. Does anyone know why?
Trial1:
Matcher matches = Pattern.compile("T\\d+").matcher("T234bird");
System.out.println(matches.lookingAt()); //after running this, find() will return false
while (matches.find())
System.out.println(matches.group());
//Output: true
Trial2:
Matcher matches = Pattern.compile("T\\d+").matcher("T234bird");
//System.out.println(matches.lookingAt()); //without this, find() will return true
while (matches.find())
System.out.println(matches.group());
//Output: T234
Trial3:
Matcher matches = Pattern.compile("T\\d+").matcher("T234bird");
while (matches.lookingAt())
System.out.println(matches.group());
//Output: T234 T234 T234 T234 ... till crash
//I understand why this happens. It's not my question but I just included it in case someone may try to suggest it
Ultimately, what I want to achieve is: First confirm that the match is at the beginning of the string, then print it. I ended up doing:
Matcher matches = Pattern.compile("T\\d+").matcher("T234bird");
if(matches.lookingAt())
System.out.println(matches.group());
//Output: T234
This solves my problem but my question is: Does anyone know why lookingAt() affect find()?
In trial 1, the call
lookingAtmatchesT234, and your subsequent call tofindstarts looking for a match at the end of the previous match. If you want to go back to the beginning of the string you need to callMatcher.reset(). This is explained in the documentation for Matcher.find():Note that
lookingAtworks withstart,end, andgroupthe same wayfinddoes, so you can just do this if you are only interested in the beginning of the string:You have to use
ifinstead ofwhilehere, becauselookingAtalways starts looking at the beginning of the string, not at the end of the previous match, sowhilejust loops forever.