Java Regex Pattern Matcher.matches() before Matcher.find() Strange behaviour
java, regex
Solution
Extracted from `Matcher.find` documentation
find
public boolean find()
Attempts to find the next subsequence of the input sequence that matches the pattern. This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.
If the match succeeds then more information can be obtained via the start, end, and group methods.
Returns: true if, and only if, a subsequence of the input sequence matches this matcher's pattern
So, since you called `Matcher.matches` which attempts to match the whole String, and you did not reset the matcher, it tried to find starting after the first match. As there is only one match, it does not find anything.
Problem
I tried this example just interchanging two lines it gives different outputs why ``` String inputString = "username@gmail.com"; String pattern="([a-z]+@)([a-z]+)(\\.[a-z]+)"; Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(inputString); ``` ///changes happens here ``` if(m.find()) { String resultString = m.replaceAll("$1xxxx$3"); System.out.println(resultString); } System.out.println(m.matches());//line to be changed ``` output : username@xxxx.com true ``` System.out.println(m.matches());//line changed if(m.find()) { String resultString = m.replaceAll("$1xxxx$3"); System.out.println(resultString); } ``` output : true