gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 19:45:08 34 4
gpt4 key购买 nike

我刚刚观察到这种行为;

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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com