4

请看下面的代码:

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

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

4

3 回答 3

3

您认为 b > c 匹配正则表达式是正确的,因为它确实如此。

但是当您调用 Matcher::find() 时,它会返回与正则表达式匹配与先前的 find() 匹配项不相交的输入的下一个子字符串。由于“b > c”以“b”开头,它是先前调用返回的“a > b”匹配的一部分,所以 find() 不会返回它。

于 2011-04-01T04:05:51.307 回答
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);
        }
    }
于 2011-04-01T05:20:41.923 回答
1

基于约翰的解决方案并添加了一些边界匹配器,这最终起作用了。

    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));
    }
于 2011-04-04T01:25:09.460 回答