因此,我想通過使用正則表達式計算字符串中括號(例如括號括起來)的數量。我在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.
非常困惑。
文檔是對這個很清楚。請參閱:http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Matcher.html#groupCount() –