828 Part II: The Java Library
found = mat.matches(); // check for a match
System.out.println("Testing Java against Java.");
if(found) System.out.println("Matches");
else System.out.println("No Match");
System.out.println();
System.out.println("Testing Java against Java SE 6.");
mat = pat.matcher("Java SE 6"); // create a new matcher
found = mat.matches(); // check for a match
if(found) System.out.println("Matches");
else System.out.println("No Match");
}
}
The output from the program is shown here:
Testing Java against Java.
Matches
Testing Java against Java SE 6.
No Match
Let’s look closely at this program. The program begins by creating the pattern that contains
the sequence “Java”. Next, aMatcheris created for that pattern that has the input sequence
“Java”. Then, thematches( )method is called to determine if the input sequence matches
the pattern. Because the sequence and the pattern are the same,matches( )returnstrue.
Next, a newMatcheris created with the input sequence “Java SE 6” andmatches( )is called
again. In this case, the pattern and the input sequence differ, and no match is found. Remember,
thematches( )function returnstrueonly when the input sequence precisely matches the
pattern. It will not returntruejust because a subsequence matches.
You can usefind( )to determine if the input sequence contains a subsequence that matches
the pattern. Consider the following program:
// Use find() to find a subsequence.
import java.util.regex.*;
class RegExpr2 {
public static void main(String args[]) {
Pattern pat = Pattern.compile("Java");
Matcher mat = pat.matcher("Java SE 6");
System.out.println("Looking for Java in Java SE 6.");
if(mat.find()) System.out.println("subsequence found");
else System.out.println("No Match");
}
}