重叠组捕获

时间:2011-04-01 03:54:31

标签: java regex regex-group

请查看以下代码:

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

我的正则表达式有什么问题吗?

3 个答案:

答案 0 :(得分:3)

你认为b&gt;你是对的。 c匹配正则表达式,因为它。

但是当你调用Matcher :: find()时,它会返回与正则表达式匹配的输入的下一个子字符串与之前的find()匹配不相交。由于“b&gt; c”以'b'开头,'b'是前一次调用返回的“a&gt; b”匹配的一部分,因此find()不会返回它。

答案 1 :(得分:2)

试试这个。

    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));
    }

更新(基于绿色解决方案)

    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);
        }
    }

答案 2 :(得分:1)

基于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));
    }