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 :
true
System.out.println(m.matches());//line changed
if(m.find())
{
String resultString = m.replaceAll("$1xxxx$3");
System.out.println(resultString);
}
output :
true
Extracted from
Matcher.finddocumentationSo, since you called
Matcher.matcheswhich 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.