如果我在 java 中运行这个正则表达式,我将收到 {ab, de, f},但我想收到 {ab、bc、de、f}。我认为 bc 无法收到,因为 bc 与 ab 字母重叠。如何更改默认行为?
最佳答案
您可以尝试使用look-ahead零宽度的机制,因此它执行的每次测试都会将光标重置到执行测试之前的位置。
只需迭代字符之间的所有位置并检查其后是否存在与正则表达式匹配的子字符串。您可以将此子字符串放入捕获组中并稍后访问它。
String input = "abcdef";
Pattern p = Pattern.compile("(?=(ab)|(bc)|(de)|(f))");
Matcher m = p.matcher(input);
while (m.find()){
for (int i=1; i<=m.groupCount(); i++){
if (m.group(i)!=null)
System.out.println("group ("+i+") -> "+m.group(i));
}
}
输出:
group (1) -> ab
group (2) -> bc
group (3) -> de
group (4) -> f
关于java - java中的正则表达式: find all _overlapping_ variants (ab)|(bc)|(de)|(f) in abcdef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28651182/