Java正则表达式 – 重叠匹配
在以下代码中:
public static void main(String[] args) { List allMatches = new ArrayList(); Matcher m = Pattern.compile("\\d+\\D+\\d+").matcher("2abc3abc4abc5"); while (m.find()) { allMatches.add(m.group()); } String[] res = allMatches.toArray(new String[0]); System.out.println(Arrays.toString(res)); }
结果是:
[2abc3, 4abc5]
我希望它是
[2abc3, 3abc4, 4abc5]
如何实现?
让匹配器尝试从后者\d+
开始下一次扫描。
Matcher m = Pattern.compile("\\d+\\D+(\\d+)").matcher("2abc3abc4abc5"); if (m.find()) { do { allMatches.add(m.group()); } while (m.find(m.start(1))); }
不确定这是否可以在Java中使用,但在PCRE中您可以执行以下操作:
(?=(\d+\D+\d+)).
说明
该技术是在先行中使用匹配组,然后“吃掉”一个字符向前移动。
-
(?=
:开始积极向前看-
(
:开始匹配组1-
\d+
:匹配数字一次或多次 -
\D+
:匹配非数字字符一次或多次 -
\d+
:匹配数字一次或多次
-
-
)
:第1组结束
-
-
)
:前瞻的结束 -
.
:匹配任何东西,这是“前进”。
在线演示
感谢Casimir et Hippolyte,它似乎真的适用于Java。 您只需要添加反斜杠并显示第一个捕获组: (?=(\\d+\\D+\\d+)).
。 在www.regexplanet.com上测试:
HamZa的上述解决方案在Java中完美运行。 如果要在文本中查找特定模式,您只需:
String regex = "\d+\D+\d+"; String updatedRegex = "(?=(" + regex + ")).";
regex
是您正在寻找和重叠的模式,您需要用(?=(" at the start and ")).
包围它(?=(" at the start and ")).
最后。