任何人都可以帮忙处理正则表达式吗?这段代码运行良好。
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");
}
}
但是这段代码返回“不匹配”。为什么?
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");
}
}
最佳答案
两者之间的唯一区别是第一个示例中的 DOTALL 标志。
如果没有该标志,字符串末尾的 \n
将与最后一个模式 (.+
) 不匹配。
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.
请注意,matches
尝试匹配整个字符串(包括您的情况下的尾随换行符),而不仅仅是尝试查找子字符串(这在 Java 中与许多其他语言不同)。
关于Java 正则表达式。奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15948247/