pattern.matcher() vs pattern.matches()

Viewed 61992

I am wondering why the results of the java regex pattern.matcher() and pattern.matches() differ when provided the same regular expression and same string

String str = "hello+";
Pattern pattern = Pattern.compile("\\+");
Matcher matcher = pattern.matcher(str);

while (matcher.find()) {
    System.out.println("I found the text " + matcher.group() + " starting at " 
        + "index " + matcher.start() + " and ending at index " + matcher.end());
}

System.out.println(java.util.regex.Pattern.matches("\\+", str));

The result of the above are:

I found the text + starting at index 5 and ending at index 6
false

I found that using an expression to match the full string works fine in case of matches(".*\\+").

8 Answers
Matcher matcher = pattern.matcher(text);

In this case, a matcher object instance will be returned which performs match operations on the input text by interpreting the pattern. Then we can use,matcher.find() to match no. of patterns from the input text.

(java.util.regex.Pattern.matches("\\+", str))

Here, the matcher object will be created implicitly and a boolean will be returned which matches the whole text with the pattern. This will work as same as the str.matches(regex) function in String.

The code equivalent to java.util.regex.Pattern.matches("\\+", str) would be:

Pattern.compile("\\+").matcher(str).matches();

method find will find the first occurrence of the pattern in the string.

Related