Can anybody help with regular expression? This code work good.
public static void main(String[] args) {
String s = "with name=successfully already exist\n";
Pattern p = Pattern.compile(".+name=.*successfully.+", Pattern.DOTALL);
java.util.regex.Matcher m = p.matcher(s);
if (m.matches()) {
System.out.println("match");
} else {
System.out.println("not match");
}
}
But this code return "not match". Why?
public static void main(String[] args) {
String s = "with name=successfully already exist\n";
if (s.matches(".+name=.*successfully.+")) {
System.out.println("match");
} else {
System.out.println("not match");
}
}
The only difference between the two is the DOTALL flag in the first example.
Without that flag, the \n at the end of the string will not match the last pattern (.+).
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#DOTALL
In dotall mode, the expression . matches any character, including a line terminator. By default this expression does not match line terminators.
Note that matches tries to match the whole string (including in your case the trailing newline), not just try to find a substring (this is different in Java than from many other languages).
The Pattern.DOTALL parameter you provide when using compile() makes it so that '.' matches 'end of line terminators'. You need to provide an inline tag to make matches() do the same. Try the following:
s.matches("(?s).+name=.*successfully(?s).+")
Cheers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With