java中的正则表达式:在abcdef中查找所有_overlapping_ variants(ab)|(bc)|(de)|(f)

如果我在java中运行此正则表达式,我将收到{ab,de,f},但我想收到{ab,bc,de,f}。 我认为bc无法收到,因为bc与ab有重叠的字母。 如何更改默认行为?

您可以尝试使用零宽度的前瞻机制,以便它执行的每个测试都会在执行测试之前将光标重置到位置。

只需遍历字符之间的所有位置,并检查它是否存在匹配正则表达式的子字符串。 您可以将此子字符串放在捕获组中,稍后再访问它。

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