计算 Java 正则表达式中的组数
javaobject oriented programmingprogramming更新于 2025/2/12 5:00:17
您可以将多个字符作为单个单元处理,方法是将它们捕获为组。您只需将这些字符放在一组括号内即可。
您可以使用 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>.";
//Regular expression to match contents of the bold tags
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 = 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
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

