Wouldn't it be easier just to use the matches()
method of String
?
Yes, for this simple program.
But the two classes Pattern
and Matcher
provide
methods that are needed for longer programs, and are, in fact,
the classes used to implement the pattern matching methods of String
.
Here are the steps to match a regular expression with a target string:
Pattern
object that contains the regular expression:
compile(String regex)
of the Pattern
class. Matcher
object linked to the target string:
matcher(String target)
method of the Pattern
object. Matcher
object now encapsulates the regular expression and the target string.Matcher
object to perform matching.
matches()
asks if the target string completely matches the regular expression.
Once a Pattern
object has been created,
it can be used repeatedly to create Matcher
objects
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 Pattern
object?