A Java String regex pattern search example

Problem: In a Java program, you want to determine whether a String contains a certain regex pattern. The pattern can be a simple String, or a more complicated regular expression (regex).

Solution: One solution is to use the Java Pattern and Matcher classes, specifically using the find method of the Matcher class. This solution is shown in the following example:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

 * Find out if a String contains a very simple pattern.
public class PatternMatcherFind
  public static void main(String[] args)
    String stringToSearch = "Four score and seven years ago our fathers ...";

    Pattern p = Pattern.compile("score");   // the pattern to search for
    Matcher m = p.matcher(stringToSearch);
    // now try to find at least one match
    if (m.find())
      System.out.println("Found a match");
      System.out.println("Did not find a match");

The output from this program is:

Found a match


This particular example is trivial, and you might be thinking that you can do the same thing with the String class and the indexOf method. For this case that is true, but when your regular expression is more complicated you’ll quickly see the usefulness of this approach. For example, you can use a pattern like "sco*" with Pattern.compile, rather than the simple string I use in this example.

Pattern-Matcher recipe

When you work with the Java Pattern and Matcher classes, you'll see this same pattern of code repeated over and over again:

  1. You have a String that you want to search.
  2. You create a Pattern for your regular expression.
  3. You create a Matcher with your Pattern and the String you want to search.

After that initial setup work, you’ll use a method like find, matches, replaceFirst, or replaceAll to work on the initial String.

In this case we use the find command to simply determine whether the original String contains the pattern we are searching for.

From the find Javadoc

The find method Javadoc includes the following description:

find() attempts to find the next subsequence of the input sequence that matches the pattern.

This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.

If the match succeeds then more information can be obtained via the start(), end(), and group() methods.

Returns true if, and only if, a subsequence of the input sequence matches this matcher's pattern