捕获组通过从左到右计数开括号来编号。要找出表达式中有多少个组,请在对象groupCount()上调用方法matcher。该groupCount()方法返回一个int显示匹配器模式中存在的捕获组数的。
package org.nhooo.example.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CountingGroupDemo {
public static void main(String[] args) {
// 定义正则表达式以查找单词“ quick”或“ lazy”或“ dog”
String regex = "(quick)|(lazy)|(dog)";
String text = "the quick brown fox jumps over the lazy dog";
// 获取所需的匹配器
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
int groupCount = matcher.groupCount();
System.out.println("Number of group = " + groupCount);
// 查找每个匹配并打印
while (matcher.find()) {
for (int i = 0; i <= groupCount; i++) {
// 第一组
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}程序的结果:
Number of group = 3 Group 0: quick Group 1: quick Group 2: null Group 3: null Group 0: lazy Group 1: null Group 2: lazy Group 3: null Group 0: dog Group 1: null Group 2: null Group 3: dog