You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取正则表达式中Lookbehind/Lookahead的关联匹配位置?

Java正则:获取包含Lookbehind的匹配范围

问题原因

你当前的正则(?<=two )three使用了零宽度正向后行断言(Lookbehind),这类断言仅负责验证位置,不会将匹配的"two "纳入最终匹配结果,因此Matcher.start()和end()仅返回"three"的位置(8-13)。

可行解决方案

要获取从"two"起始到"three"结束的范围(4-13),有两种可靠方式:

方案1:将Lookbehind内容纳入匹配范围

直接调整正则,把需要包含的"two "作为匹配的一部分(无需再用Lookbehind),这样整个匹配结果就是"two three",直接获取其起止位置即可:

String text = "one two three";
String pattern = "(two )three";
Matcher m = pattern.matcher(text);
while(m.find()){
    System.out.println(m.start() + " - " + m.end()); // 输出 4 - 13
}

方案2:保留Lookbehind,手动计算起始位置

如果因业务需求必须使用Lookbehind(比如Lookbehind的验证逻辑更复杂),可通过Lookbehind内容的长度,反向推导起始位置:

String text = "one two three";
String pattern = "(?<=two )three";
Matcher m = pattern.matcher(text);
// 对应Lookbehind中的内容,需保证长度固定(Java要求Lookbehind为固定/有限长度)
String lookbehindContent = "two ";
while(m.find()){
    int start = m.start() - lookbehindContent.length();
    int end = m.end();
    System.out.println(start + " - " + end); // 输出 4 - 13
}

注意:Java 9及以上支持有限长度的可变Lookbehind(如(?<=a{1,3})),这种情况下需先通过额外逻辑确定实际匹配的Lookbehind长度,再进行计算。

内容的提问来源于stack exchange,提问作者annamaria07

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 15:10:16