Might the same regular expression be found in several locations in a string?
Yes.
find()
continues from where it Left Off
The find()
method of a Matcher
starts at the left of the
subject string the first time it is called.
If it finds a matching substring, it saves the substring in group 0, and remembers
where it stopped searching
When find()
is called a second time, it starts up where it left off
and attempts to find another matching substring.
You can keep doing this until it returns false (when it has searched to the end of
the string without finding a match).
Here is an example program:
import java.util.regex.*; public class ManyFind { public static void main(String[] args) { int sum = 0; boolean atLeastOneFound = false; Pattern pattern = Pattern.compile( "\\d+" ); Matcher matcher = pattern.matcher ( "Add 10 up 23 all 55 the 12 numbers 100 in 77 this 33 sentence." ); // match the regular expression with the target string while ( matcher.find() ) { atLeastOneFound = true; System.out.println( "I found: " + matcher.group(0) + " and am adding it to the sum"); sum += Integer.parseInt( matcher.group(0) ); } if ( atLeastOneFound ) System.out.println( "\nThe sum is: " + sum); else System.out.println( "\nNo numbers found in the sentence" ); } }
The program writes:
I found: 10 and am adding it to the sum I found: 23 and am adding it to the sum I found: 55 and am adding it to the sum I found: 12 and am adding it to the sum I found: 100 and am adding it to the sum I found: 77 and am adding it to the sum I found: 33 and am adding it to the sum The sum is: 310
Notice that the substrings saved in the groups change after each call.
Do you think that matches()
and lookingAt()
continue from where they left off in the previous call?