2011-12-06 21 views
0

因此,我想通過使用正則表達式計算字符串中括號(例如括號括起來)的數量。我在matcher類中找到了這個方法「groupCount」。所以我認爲這可以幫助我。如何計算Java正則表達式中的字符串中的括號數

groupCount在JavaDoc中說:「任何小於或等於此方法返回的值的非負整數保證是此匹配器的有效組索引。」所以我想像

m.group(m.groupCount()); 

應該始終工作。錯誤的...

下面是一些測試代碼我寫道:

public class TestJavaBracketPattern { 

    public static void main(String[] args) { 
     Matcher m = Pattern.compile("(\\))").matcher(")"); 
     System.out.println(m.group(m.groupCount())); 
    } 

} 

現在在這裏,我希望以匹配正則表達式閉括號(稱爲\)),並得到一個單一的比賽。正則表達式是(\)) - 它應該匹配包含閉括號符號的組。但它只是拋出一些異常(java.lang.IllegalStateException:未找到匹配)。

接下來,我試圖匹配在沒有匹配:

public class TestJavaBracketPattern { 

    public static void main(String[] args) { 
     Matcher m = Pattern.compile("(\\))").matcher("("); 
     System.out.println(m.group(m.groupCount())); 
    } 

} 

我得到相同的異常。實際上,在這兩種情況下,我發現groupCount方法返回1.

非常困惑。

+0

文檔是對這個很清楚。請參閱:http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Matcher.html#groupCount() –

回答

1

以下是否過於務實?

@Test 
void testCountBrackets() { 
    String s = "Hello) how)are)you("; 
    System.out.println(s.length() - s.replaceAll("\\)", "").length()); // 3 
} 

(當然,這是假定你要搜索一個真正的RE東西不僅僅是一個支架更爲複雜。否則,只需要使用s.replace(")","")

+0

實際上,這是我見過的最優雅的東西 – Kidburla

+0

謝謝。但作爲一個單元測試,這是一個完全失敗:-) – mgaert

+0

這不是一個失敗...我試着運行它,它每次都報告成功(而不是失敗)! ;-) – Alderath

1

groupCount返回模式中的組數,不在匹配結果中。

你將不得不這樣做;

Matcher m = Pattern.compile("(\\))").matcher("Hello) how)are)you("); 
int count = 0; 
while (m.find()) { 
    count++; 
} 
System.err.format("Found %1$s matches\n", count); 
0

請使用下面的代碼。

int count1 = StringUtils.countMatches("fi(n)d (i)n (the st)(ri)ng", "("); //關於 '('

int count2 = StringUtils.countMatches("fi(n)d (i)n (the st)(ri)ng", ")"); //爲 ')'

int totalCount = count1+count2; 

StringUtils存在於common-lang庫。

1

你並沒有真正開始搜索,這是發生異常的原因。

Matcher.groupCount()返回Pattern中的多少個組,而不是結果。

Matcher.group()返回前一次匹配期間給定組捕獲的輸入子序列。

您可以參考this page

我改變你這樣的代碼,

public class TestJavaBracketPattern { 

    public static void main(String[] args) { 
     Matcher m = Pattern.compile("(\\))").matcher(")"); 
     if (m.find()) {   
     System.out.println(m.group(m.groupCount())); 
     } 
    } 
} 

添加m.find(),其結果是:

1 
) 
相關問題