Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pattern.matcher() vs pattern.matches()

Tags:

java

regex

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(".*\\+").

like image 737
samarjit Avatar asked Oct 05 '10 10:10

samarjit


People also ask

What is pattern and matcher?

A pattern is a compiled representation of a regular expression. Patterns are used by matchers to perform match operations on a character string. A regular expression is a string that is used to match another string, using a specific syntax.

What is pattern matches in Java?

Pattern matching has modified two syntactic elements of the Java language: the instanceof keyword and switch statements. They were both extended with a special kind of patterns called type patterns. There is more to come in the near future.

What is matcher in regex?

regex. Matcher ) is used to search through a text for multiple occurrences of a regular expression. You can also use a Matcher to search for the same regular expression in different texts.


2 Answers

pattern.matcher(String s) returns a Matcher that can find patterns in the String s. pattern.matches(String str) tests, if the entire String (str) matches the pattern.

In brief (just to remember the difference):

  • pattern.matcher - test if the string contains-a pattern
  • pattern.matches - test if the string is-a pattern
like image 173
Andreas Dolk Avatar answered Oct 06 '22 07:10

Andreas Dolk


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

Pattern.matches(String regex, CharSequence input) compiles the regex into a Matcher and returns Matcher.matches().

Matcher.matches attempts to match the entire region (string) against the pattern (Regex).

So, in your case, the Pattern.matches("\\+", str) returns a false since str.equals("+") is false.

like image 35
Buhake Sindi Avatar answered Oct 06 '22 09:10

Buhake Sindi