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(".*\\+")
.
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.
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.
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.
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 patternpattern.matches
- test if the string is-a patternMatcher.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With