2011-04-01 68 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