Regular expressions in Java:
using the Pattern and Matcher classes

There are simple methods for using using regular expressions in Java, such as String.replaceAll() and String.matches(). For more options— and sometimes better performance— when using regular expressions, we can use the Pattern and Matcher classes. (In fact, methods such as String.matches() are convenience wrappers around Pattern and Matcher.)

Here is how to use Pattern and Matcher:

(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 find() or 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();
}

We can also use the find() method to determine whether or not the expression occurs anywhere in the string.

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.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.