2011-04-01 66 views
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

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

回答

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

这适用于此特定字符串“a < b > c> d”,但是当我将其更改为“abc> x> y”时,它会失败。如果我将正则表达式更改为“(?=(\\ w + \\ s * [<>] {1} \\ s * \\ w +))。”,则输出:abc y,其中“bc 2011-04-02 06:10:03

+0

通过添加一些边界匹配器,我终于使其工作!看到我对这个问题的回答。约翰得到了信用但是;) – 2011-04-04 01:22:19

+0

太棒了!为了支持CDN js路径(包括'http:'),正则表达式的一个非常小的更新:(?= [\\ s,;] + |(?<![\\ w \\/\\ - \ \:])([\\瓦特\\/\\ - \\] + \\ S * [<>] \\ S * [\\瓦特\\/\\ - \\ .:] +) ) – 2011-04-05 05:20:17

3

你在你的思想,B> C,因为它正则表达式匹配是正确的。

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

+1

任何想法如何使它匹配“b> c”在这种情况下? – 2011-04-02 06:11:49

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

唯一的限制是你需要在字符串前面插入一个空格,否则你会丢失第一个项目 – 2011-04-04 01:27:34

+0

你不需要'[\\ s,; $] *'。 ?'“(= [\\ S,;] +([。\\瓦特\\/\\ - \\] + \\ S * [<>] \\ S * [\\瓦特\\/\\ - \\。] +))“'就够了。 – 2011-04-04 06:21:36

+0

试试我更新的答案。 – 2011-04-04 07:01:07