Wouldn't it be easier just to use the
matches() method of
Yes, for this simple program.
But the two classes
methods that are needed for longer programs, and are, in fact,
the classes used to implement the pattern matching methods of
Here are the steps to match a regular expression with a target string:
Patternobject that contains the regular expression:
compile(String regex)of the
Matcherobject linked to the target string:
matcher(String target)method of the
Matcherobject now encapsulates the regular expression and the target string.
Matcherobject to perform matching.
matches()asks if the target string completely matches the regular expression.
Pattern object has been created,
it can be used repeatedly to create
for a succession of strings.
For example, to search a text file,
you could create a
Pattern object for the pattern,
then use it to create a
Matcher object for each line of the file.
If you now want to match a different regular expression
must you create a new