2016-11-08 73 views
0

我只寫了2小時的代碼,認爲Matcher.group()返回了在正則表達式中進行匹配的組的編號/ id。我所做的簡單的例子:獲取在正則表達式中進行匹配的組的編號/編號

// Group -1- -2- 
Pattern p = Pattern.compile("(abc)|(def)"); 
String t = "abc abc def def abc"; 

for (Matcher m = p.matcher(t); m.find();) { 
    System.out.print(m.group()); 
} 

我認爲這將輸出1, 1, 2, 2, 1,該集團每場比賽的數量。相反,它實際上會返回組匹配的部分。有沒有其他方法或任何方法來實現我想要的結果?

+0

模式類型不匹配:不能從字符串轉換爲模式? – JordanGS

+0

我的錯誤對不起 –

回答

2

您可以檢查group個結果,看看哪一個被匹配:

for (Matcher m = p.matcher(t); m.find();) { 
    if (m.group(1) != null) { 
     System.out.print("1, "); 
    } else { 
     System.out.print("2, "); 
    } 
} 

編輯:如果你有很多團體和不想硬編碼他們,你也可以遍歷他們相反(假設他們仍然是獨家):

for (Matcher m = p.matcher(t); m.find();) { 
    for (int i = 1; i <= m.groupCount(); i++) { 
     if (m.group(i) != null) { 
      System.out.print(i + ", "); 
      break; 
     } 
    } 
} 
+0

我想過了,但你看,我的正則表達式是巨大的(> 1000個字符),我的文本也是如此,時間是一個問題。它會影響性能嗎? –

+0

有多少組? – shmosel

+0

二十一組 –