计算Java正则表达式的组数
通过将多个字符捕获为一组,可以将多个字符视为一个单元。您只需要将这些字符放在一组括号内即可。
您可以使用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
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿