pattern.matcher() vs pattern.matches()
Solution 1:
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
Solution 2:
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.