java – 重叠组捕获
作者:互联网
请看下面的代码:
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 但我实际上期望一个< b,b> c,c> d. 我的正则表达式有什么问题吗?
解决方法:
试试这个.
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);
}
}
标签:java,regex,regex-group 来源: https://codeday.me/bug/20190531/1187988.html