Java中的Matcher groupCount()方法与示例
java.util.regex.Matcher类表示执行各种匹配操作的引擎。此类没有构造函数,可以使用matches()
类java.util.regex.Pattern的方法创建/获取此类的对象。
这个(Matcher)类的groupCount()方法计算当前匹配项中的捕获组数。
例子1
import java.util.regex.Matcher; import java.util.regex.Pattern; public class GroupTest { public static void main(String[] args) { String regex = "(.*)(\\d+)(.*)"; String input = "This is a sample Text, 1234, with numbers in between."; //创建一个模式对象 Pattern pattern = Pattern.compile(regex); //匹配字符串中的已编译模式 Matcher matcher = pattern.matcher(input); if(matcher.find()) { System.out.println("First group match: "+matcher.group(1)); System.out.println("Second group match: "+matcher.group(2)); System.out.println("Third group match: "+matcher.group(3)); System.out.println("Number of groups capturing: "+matcher.groupCount()); } } }
输出结果
First group match: This is a sample Text, 123 Second group match: 4 Third group match: , with numbers in between. Number of groups: 3
例子2
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 wit 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