我有這樣的模式:Java的模式與團體
Pattern p = Pattern.compile("([0-9]){11}");
我的問題是如何從集團獲得所有數字和概括。 我與此代碼嘗試,但不工作:
Matcher matcher = p.matcher(field);
int result = 0;
if (matcher.matches()) {
for (int i = 0; i <= matcher.groupCount(); i++) {
String number = matcher.group(i + 1);
result += Integer.parseInt(number);
}
return result;
} else {
return -1;
}
它找到的唯一的組是最後一組。
這是因爲'.matches()'只有每輸入匹配了一次。 – 2013-02-08 21:58:45
和['Matcher#groupCount()'](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#groupCount())返回捕獲組的數量在匹配者的**模式**中。 – jlordo 2013-02-08 21:59:49
你是想總結個人的單個數字嗎?!? ''1234「= 1 + 2 + 3 + 4' – 2013-02-08 22:04:30