This has nothing to do with the MULTILINE flag; what you're seeing is the difference between the find()
and matches()
methods. find()
succeeds if a match can be found anywhere in the target string, while matches()
expects the regex to match the entire string.
Pattern p = Pattern.compile("xyz");
Matcher m - p.matcher("123xyzabc");
System.out.println(m.find()); // true
System.out.println(m.matches()); // false
Matcher m - p.matcher("xyz");
System.out.println(m.matches()); // true
Furthermore, MULTILINE
doesn't mean what you think it does. Many people seem to jump to the conclusion that you have to use that flag if your target string contains newlines--that is, if it contains multiple logical lines. I've seen several answers here on SO to that effect, but in fact, all that flag does is change the behavior of the anchors, ^
and $
.
Normally ^
matches the very beginning of the target string, and $
matches the very end (or before a newline at the end, but we'll leave that aside for now). But if the string contains newlines, you can choose for ^
and $
to match at the start and end of any logical line, not just the start and end of the whole string, by setting the MULTILINE flag.
So forget about what MULTILINE
means and just remember what it does: changes the behavior of the ^
and $
anchors. DOTALL
mode was originally called "single-line" (and still is in some flavors, including Perl and .NET), and it has always caused similar confusion. We're fortunate that the Java devs went with the more descriptive name in that case, but there was no reasonable alternative for "multiline" mode.
In Perl, where all this madness started, they've admitted their mistake and gotten rid of both "multiline" and "single-line" modes in Perl 6 regexes. In another twenty years, maybe the rest of the world will have followed suit.