java - 正则表达式在多行模式下不匹配空字符串 (Java)

标签 java regex

我刚刚观察到这种行为;

Pattern p1 = Pattern.compile("^$");
Matcher m1 = p1.matcher("");
System.out.println(m1.matches()); /* true */

Pattern p2 = Pattern.compile("^$", Pattern.MULTILINE);
Matcher m2 = p2.matcher("");
System.out.println(m2.matches()); /* false */

令我感到奇怪的是,最后一个陈述是错误的。这就是文档所说的;

By default, the regular expressions ^ and $ ignore line terminators and only match at the beginning and the end, respectively, of the entire input sequence. If MULTILINE mode is activated then ^ matches at the beginning of input and after any line terminator except at the end of input. When in MULTILINE mode $ matches just before a line terminator or the end of the input sequence. http://docs.oracle.com/javase/1.4.2...

从我得到的结果来看,它应该匹配吗?以下内容使事情变得更加困惑;

Pattern p3 = Pattern.compile("^test$");
Matcher m3 = p3.matcher("test");
System.out.println(m3.matches()); /* true */

Pattern p4 = Pattern.compile("^test$", Pattern.MULTILINE);
Matcher m4 = p4.matcher("test");
System.out.println(m4.matches()); /* true */

那这是什么?我如何理解这一点?我希望有人能对此有所了解,将不胜感激。

最佳答案

If MULTILINE mode is activated then ^ matches at the beginning of input and after any line terminator except at the end of input.

由于你在输入的末尾,^无法在多行模式下匹配。

这令人惊讶,甚至令人作呕,但根据其文档仍然如此。

关于java - 正则表达式在多行模式下不匹配空字符串 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8896201/

相关文章:

java - '+i'在Java中是什么意思?

JavaScript Regex 仅当字符仅出现后跟字母数字字符时才匹配

java - 正则表达式非单词边界和空格

java - 重构正则表达式模式 - Java

javascript - 正则表达式全局匹配术语直到分隔符,结果不带术语/分隔符

java - 如何标准化混合的 WAV 文件

java - Gmail API 配置问题(Java 中)

java - 如何使用 Struts 2 在 Apache Tomcat 应用程序中建立数据库连接

java - 如何根据对象的某个属性对对象数组进行排序?

php sed 类似功能