Java: How to test if a String contains a case-insensitive regex pattern

Java String FAQ: How can I tell if a Java String contains a given regular expression (regex) pattern?

In a Java program, you want to determine whether a String contains a case-insensitive regular expression (regex). You don't want to manipulate the String or extract the match, you just want to determine whether the pattern exists at least one time in the given String.

Solution: Use the Java Pattern and Matcher classes, supply a regular expression (regex) to the Pattern class, and use the Pattern.CASE_INSENSITIVE flag of the Pattern class. Then use the find method of the Matcher class to see if there is a match.

This is shown in the following Java source code example:

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

/**
 * Find out whether a given String contains a simple regular
 * expression (regex).
 */
public class PatternMatcherFind3Regex
{
  public static void main(String[] args)
  {
    // the string we want to search
    String stringToSearch = "FOUR SCORE AND SEVEN YEARS AGO OUR FATHERS ...";
    
    // search for this simple pattern
    String patternToSeachFor = " ye.* ";

    // set everything up
    Pattern p = Pattern.compile(patternToSeachFor, Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(stringToSearch);
    
    // now see if we find a match
    if (m.find())
      System.out.println("Found a match");
    else
      System.out.println("Did not find a match");
  }
}

The output from this program is:

Found a match

Discussion

This is a simple example intended to show how to use a simple regular expression and the Pattern.CASE_INSENSITIVE flag when creating a Pattern. In this case the regular expression I used was this:

" ye.* "

Combined with the Pattern.CASE_INSENSITIVE flag, this regular expression can be read as, "Ignoring upper and lower case, look for a blank space, followed by the characters 'y' and 'e', followed by many occurrences of any character, and then one more blank space."

Note that when using the find method there may be more than one occurrence of your pattern in the Java String. In this example I'm not worried about that, I'm just looking to see if I have at least one match.

Of course your regular expressions can be as complicated as you need them to be, and I will show many more regular expression patterns on this blog.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.