The Java String ‘matches’ method

Problem: In a Java program, you want to determine whether a String contains a pattern, and you’d rather use the String matches method than use the Pattern and Matcher classes.

Solution: Use the String matches method, but it’s very important to remember that the regex pattern you define must match the entire string.

A complete String “matches” example

Here’s a complete Java program that shows two patterns that attempt to match a String, including one that does work, and one that intentionally does not work:

/**
 * Demonstrates how to use the String.matches() method, including
 * the need to match the entire string in your patterns.
 */
public class StringMatches1
{
  public static void main(String[] args)
  {
    String stringToSearch = "Four score and seven years ago our fathers ...";
    
    // WRONG: this prints "false", because the search pattern doesn't
    //        match entire string
    System.out.println("Try 1: " + stringToSearch.matches("seven"));
    
    // CORRECT: this prints "true" because the pattern does match the 
    //          entire string 
    System.out.println("Try 2: " + stringToSearch.matches(".*seven.*"));
  }
}

The output from this program is:

Try 1: false
Try 2: true

Discussion

While this example is trivial, it’s intentionally trivial, so I can demonstrate a common problem that developers run into when using the matches method, specifically the need to define a pattern that matches the entire String that you’re trying to test against.

In a more complicated example you might try to look for a pattern like this:

<code>\\S+</code>

But again, you need to make sure you add the extra characters to make sure your pattern matches the entire line.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.