通过将多个字符捕获为一组,可以将多个字符视为一个单元。您只需要将这些字符放在一组括号内即可。
您可以使用Matcher类的groupCount()方法计算当前匹配项中的组数。此方法计算当前匹配项中的捕获组数并返回。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String str1 = "<p>This <b>is</b> an <b>example</b> HTML <b>script</b> where <b>ever</b> alternative <b>word</b> is <b>bold</b></p>.";
//正则表达式以匹配粗体标签的内容
String regex = "(t(\\S+)t)(\\s)";
String str = "the words tit tat tweet tostff tact that tilt text. start and end with the letter t ";
//创建一个模式对象
Pattern pattern = Pattern.compile(regex);
//匹配字符串中的已编译模式
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(0));
}
System.out.println("Total capturing groups: "+matcher.groupCount());
}
}输出结果
tit tat tweet tact that tilt text tart Total capturing groups: 3