Java regex lookbehind无法像js regex lookbehind

问题描述 投票:1回答:2

我有这个目标:

给出字符串:"Part1-part2-part3-part4-part5"在第二次出现“-”时将其拆分,所以我期望一个数组[ "Part1-part2", "part3-part4-part5" ]

我做了什么:

"Part1-part2-part3-part4-part5".split("(?<=^\\w+-\\w+)-"

但是在jdk 8上结果:它找不到第二个'-',并返回整个字符串的匹配项。证据:https://ideone.com/myWppm

但是当我尝试在线正则表达式处理网站和node.js(或chrome)时[相信我,现代js支持向后看],结果是预期的。证据:https://ideone.com/ttQWNr

我目前正在使用的提示(没有资格作为解决方案):

使用先行而不是向后看,从末尾第三次出现'-'"Part1-part2-part3-part4-part5".split("-(?=\\w+-\\w+-\\w+$)");

java regex regex-lookarounds lookbehind
2个回答
0
投票

代替使用split(),使用匹配:

String input = "Part1-part2-part3-part4-part5";
String regex = "(\\w+-\\w+)-(.*)"
String[] result; // just to simulate result of split()
Matcher m = Pattern.compile(regex).matcher(input);
if (m.matches()) {
    result = new String[] { m.group(1), m.group(2) };
} else {
    result = new String[] { input };
}

当然,这需要更多代码,但是您可以轻松地增强正则表达式以执行更多验证,例如,除了-(显然还有_)以外,没有特殊字符,即使对于第二个破折号之后的文本也是如此。


0
投票

Java不支持可变宽度后向。假设您的输入字符串always有五个连字符分隔的术语,我们可以改为在分割之前检查前面是否有两个连字符来表示分隔逻辑:

String input = "Part1-part2-part3-part4-part5";
String[] parts = input.split("-(?=[^-]+-[^-]+-[^-]+$)");
System.out.println(Arrays.toString(parts));

此打印:

[Part1-part2, part3-part4-part5]
© www.soinside.com 2019 - 2024. All rights reserved.