Java 的 MatchResult groupCount() 方法及其示例。
java.util.regex.MatcheResult 接口提供方法来检索匹配的结果。
你可以使用 Matcher 类中的 toMatchResult() 方法获取此接口的对象。此方法返回一个表示当前匹配器匹配状态的 MatchResult 对象。
此接口的 groupCount() 方法可以计数并返回当前对象正则表达式中的组数。
示例
import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupCount {
public static void main( String args[] ) {
String regex = "(.*)(\d+)(.*)";
//Reading input from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
//Instantiating the Pattern class
Pattern pattern = Pattern.compile(regex);
//Instantiating the Matcher class
Matcher matcher = pattern.matcher(input);
//verifying whether a match occurred
if(matcher.find()) {
System.out.println("Match found");
}
MatchResult res = matcher.toMatchResult();
int count = res.groupCount();
System.out.println("No.of groups: "+count);
}
}输出
Enter input text: This is a sample Text, 123 Match found No.of groups: 3
Advertisement
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP