Java: How to perform a case-insensitive search using the String ‘matches’ method

Problem: In a Java program, you want to determine whether a String contains a pattern, you want your search to be case-insensitive, and you want to use String matches method than use the Pattern and Matcher classes.

Solution: Use the String matches method, and include the magic (?i:X) syntax to make your search case-insensitive. (Also, remember that when you use the matches method, your regex pattern must match the entire string.)

Here's the source code for a complete Java program that demonstrates this case-insensitive pattern matching technique:

/**
 * Demonstrates how to perform a case-insensitive pattern
 * match using String and the String.matches() method.
 */
public class StringMatchesCaseInsensitive
{
  public static void main(String[] args)
  {
    String stringToSearch = "Four score and seven years ago our fathers ...";
    
    // this won't work because the pattern is in upper-case
    System.out.println("Try 1: " + stringToSearch.matches(".*SEVEN.*"));
    
    // the magic (?i:X) syntax makes this search case-insensitive, so it returns true
    System.out.println("Try 2: " + stringToSearch.matches("(?i:.*SEVEN.*)"));
  }
}

The output from this program is:

Try 1: false
Try 2: true

Discussion

This is a trivial example that you could solve using other techniques, but when you have a more complex pattern that you're trying to find, this "magic" case-insensitive syntax can come in handy.

For more information on this syntax see the Pattern javadoc page on Sun's web site.

Add new comment

Anonymous format

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