[英]Overlapping group capturing
请看下面的代码:
public static void main(String[] args) {
String s = "a < b > c > d";
String regex = "(\\w\\s*[<>]\\s*\\w)";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
int i = 0;
while (m.find()) System.out.println(m.group(i++));
}
上述程序的输出是: a < b, c > d
但我实际上期望a < b, b > c, c > d
。
我的正则表达式有什么问题吗?
你认为b> c匹配正则表达式是正确的,因为它确实如此。
但是,当你调用匹配器:: find()方法,它返回其先前找到匹配的正则表达式,是不相交输入的下一个子()相匹配。 由于“b> c”以'b'开头,'b'是前一次调用返回的“a> b”匹配的一部分,因此find()不会返回它。
试试这个。
String s = "a < b > c > d";
String regex = "(?=(\\w{1}\\s{1}[<>]{1}\\s{1}\\w{1})).";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
while(m.find()) {
System.out.println(m.group(1));
}
更新(基于green的解决方案) :
String s = " something.js > /some/path/to/x19-v1.0.js < y < z < a > b > c > d";
String regex = "(?=[\\s,;]+|(?<![\\w\\/\\-\\.])([\\w\\/\\-\\.]+\\s*[<>]\\s*[\\w\\/\\-\\.]+))";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
while (m.find()) {
String d = m.group(1);
if(d != null) {
System.out.println(d);
}
}
基于John的解决方案并添加一些边界匹配器,这最终有效。
String s = " something.js > /some/path/to/x19-v1.0.js < y < z < a > b > c > d";
String regex = "(?=[\\s,;]+([\\w\\/\\-\\.]+\\s*[<>]\\s*[\\w\\/\\-\\.]+)[\\s,;$]*).";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
while(m.find()) {
System.out.println(m.group(1));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.