Chapter 27: NIO, Regular Expressions, and Other Packages 829
The output is shown here:
Looking for Java in Java SE 6.
subsequence found
In this case,find( )finds the subsequence “Java”.
Thefind( )method can be used to search the input sequence for repeated occurrences
of the pattern because each call tofind( )picks up where the previous one left off. For example,
the following program finds two occurrences of the pattern “test”:
// Use find() to find multiple subsequences.
import java.util.regex.*;
class RegExpr3 {
public static void main(String args[]) {
Pattern pat = Pattern.compile("test");
Matcher mat = pat.matcher("test 1 2 3 test");
while(mat.find()) {
System.out.println("test found at index " +
mat.start());
}
}
}
The output is shown here:
test found at index 0
test found at index 11
As the output shows, two matches were found. The program uses thestart( )method to
obtain the index of each match.
Using Wildcards and Quantifiers
Although the preceding programs show the general technique for usingPatternandMatcher,
they don’t show their power. The real benefit of regular expression processing is not seen until
wildcards and quantifiers are used. To begin, consider the following example that uses the +
quantifier to match any arbitrarily long sequence of Ws.
// Use a quantifier.
import java.util.regex.*;
class RegExpr4 {
public static void main(String args[]) {
Pattern pat = Pattern.compile("W+");
Matcher mat = pat.matcher("W WW WWW");
while(mat.find())
System.out.println("Match: " + mat.group());
}
}