go to previous page   go to home page   go to next page

Wouldn't it be easier just to use the matches() method of String ?

Answer:

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.


Steps to a Match

Objects involved in Matching

Here are the steps to match a regular expression with a target string:

  1. Create a Pattern object that contains the regular expression:
    • Use the static method compile(String regex) of the Pattern class.
  2. Create a Matcher object linked to the target string:
    • Use the matcher(String target) method of the Pattern object.
    • The Matcher object now encapsulates the regular expression and the target string.
  3. Invoke any of several methods of the Matcher object to perform matching.
    • matches() asks if the target string completely matches the regular expression.
    • Other methods do other useful things.

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.


QUESTION 3:

If you now want to match a different regular expression must you create a new Pattern object?