I thought I had understood the way those delimiters match on Java regexps, and how the multiline modifier affects it, but in the end I can't get this simple code sample to give me the expected result.
Also read several simmilar questions on SO and the solution is always using the (?m)
modifier. So, what is wrong with this example?
public class Test{
public static void main(String []args){
System.out.println("foo\nTAG\nbar".matches("(?m)^TAG$") ? "matches" : "dont match");
}
}
Prints don't match. Can be tested at http://www.compileonline.com/compile_java_online.php
Matches method tries to match the whole input string. So change your regex like below to get a match. In multiline mode (?m)
, dot won't match a newline character. To match any character including newline , you need to use [\S\s]
which matches a space or non-space character.
In Dotall mode (?s)
, you could simply use .*
to match any character (including newline character) zero or more times.
Modifiers can even be combined as (?ms)
to get advantage of the best of both modes.
System.out.println("foo\nTAG\nbar".matches("(?m)[\\s\\S]*^TAG$[\\s\\S]*") ? "matches" : "dont match");
System.out.println("foo\nTAG\nbar".matches("(?s).*?(^|\n)TAG(\n|$).*") ? "matches" : "dont match");
System.out.println("foo\nTAG\nbar".matches("(?ms).*?^TAG$.*") ? "matches" : "dont match");
Output:
matches
matches
matches