我在 Java 的正则表达式实现中发现了一些意外行为。使用 java.util.regex.Pattern
时和 java.util.regex.Matcher
, 使用 Matcher 的 find()
时,以下正则表达式 不 正确匹配输入 "Merlot"
方法:
((?:White )?Zinfandel|Merlot)
如果我改变最外层匹配组内表达式的顺序,Matcher 的 find()
方法确实匹配。
(Merlot|(?:White )?Zinfandel)
这里有一些说明问题的测试代码。
RegexTest.java
import java.util.regex.*;
public class RegexTest {
public static void main(String[] args) {
Pattern pattern1 = Pattern.compile("((?:White )?Zinfandel|Merlot)");
Matcher matcher1 = pattern1.matcher("Merlot");
// prints "No Match :("
if (matcher1.find()) {
System.out.println(matcher1.group(0));
} else {
System.out.println("No match :(");
}
Pattern pattern2 = Pattern.compile("(Merlot|(?:White )?Zinfandel)");
Matcher matcher2 = pattern2.matcher("Merlot");
// prints "Merlot"
if (matcher2.find()) {
System.out.println(matcher2.group(0));
} else {
System.out.println("No match :(");
}
}
}
预期的输出是:
Merlot
Merlot
但实际输出是:
No Match :(
Merlot
我已经验证了这种意外行为存在于 Ubuntu linux 上的 Java 版本 1.7.0_11 和 OSX 10.8.2 上的 Java 版本 1.6.0_37 中。我将此行为作为错误报告给 Oracle昨天收到一封自动电子邮件,告诉我我的错误报告已收到,内部审查 ID 为 2441589。当我在他们的错误数据库中搜索该 ID 时,我找不到我的错误报告。 (你能听到蟋蟀的声音吗?)
我是否发现了 Java 可能经过彻底测试和使用的正则表达式实现中的一个错误(在 2013 年很难相信),还是我做错了什么?
最佳答案
以下内容:
import java.util.regex.*;
public class T {
public static void main( String args[] ) {
System.out.println( Pattern.compile("(a)?bb|c").matcher("c").find() );
System.out.println( Pattern.compile("(a)?b|c").matcher("c").find() );
}
}
打印
false
true
开:
- JDK 1.7.0_13
- JDK 1.6.0_24
以下内容:
import java.util.regex.*;
public class T {
public static void main( String args[] ) {
System.out.println( Pattern.compile("((a)?bb)|c").matcher("c").find() );
System.out.println( Pattern.compile("((a)?b)|c").matcher("c").find() );
}
}
打印:
true
true
关于java - Java 正则表达式实现中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14712932/