Regular expressions in Java:
using the Pattern and Matcher classes

So far, our discussion has focussed mainly on the content of regular expressions. We haven't been too concerned on how to apply regular expressions, other than by stating that we can use the String.matches() method to perform the match.

In some cases, we need to use a slightly more long-winded way to perform the match, but one which ultimately gives us more flexibility and can improve performance. Specifically, we use two classes of the java.util.regex package: Pattern and Matcher. The procedure is as follows:

(1) Compile the expression into a Pattern object

We call the static method Pattern.compile(), passing in the expression. This method returns a Pattern object. Hanging off this object is an internal representation of the pattern in a form that makes it efficient to perform matches.

Pattern patt = Pattern.compile(".*?[0-9]{10}.*");

(2) Whenever we need to perform a match, construct a Matcher object

To check whether a particular string matches the pattern, we call the matcher() method on the Pattern object, passing in the string to match:

Matcher m = patt.matcher(str);

(3) Call matches() on the Matcher

The third step is to call the matches() method on the Matcher we have just created, which returns a boolean indicating whether or not the string passed into the matcher() method matches the regular expression. The code thus looks as follows:

public boolean containsTenDigits(String str) {
  Pattern patt = Pattern.compile(".*?[0-9]{10}.*");
  Matcher m = patt.matcher(str);
  return m.matches();

Why use Pattern and Matcher?

You may be wondering what the point of this rather long-winded way of matching an expression. On the next page, we'll look at when to use the Pattern/Matcher paradigm.