The groupCount() method of the Matcher class is used to return the number of capturing groups present in the regular expression associated with the matcher. Capturing groups are created by enclosing a part of the regular expression within parentheses ().
- Does not include group 0 (the entire matched expression).
- Commonly used when processing multiple capturing groups dynamically.
import java.util.regex.*;
public class Geeks {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("(Java)(\\d+)");
Matcher matcher = pattern.matcher("Java17");
System.out.println("Capturing Groups: "
+ matcher.groupCount());
}
}
Output
Capturing Groups: 2
Explanation: The regular expression (Java)(\\d+) contains two capturing groups:
- Group 1: (Java)
- Group 2: (\\d+)
Hence, the groupCount() method returns 2.
Syntax
public int groupCount()
- Parameters: This method does not accept any parameters.
- Return Value: Returns the total number of capturing groups in the matcher's regular expression.
Example: Count Capturing Groups in Date Format
import java.util.regex.*;
public class Geeks {
public static void main(String[] args) {
// Regex with three capturing groups:
// (Day) (Month) (Year)
Pattern pattern = Pattern.compile("(\\d{2})-(\\d{2})-(\\d{4})");
Matcher matcher = pattern.matcher("15-07-2026");
// Display total capturing groups
System.out.println("Number of Groups: "
+ matcher.groupCount());
}
}
Output
Number of Groups: 3
Explanation: The regular expression contains three capturing groups for day, month, and year, so groupCount() returns 3.
Example: Count Groups and Print Each Group
import java.util.regex.*;
public class Geeks {
public static void main(String[] args) {
// First Name, Last Name and Age
Pattern pattern = Pattern.compile("(\\w+)\\s(\\w+)\\s(\\d+)");
Matcher matcher = pattern.matcher("John Smith 28");
if (matcher.find()) {
// Print total capturing groups
System.out.println("Total Groups: "
+ matcher.groupCount());
// Display each captured group
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": "
+ matcher.group(i));
}
}
}
}
Output
Total Groups: 3 Group 1: John Group 2: Smith Group 3: 28
Explanation: The regex has three capturing groups that extract the first name, last name, and age. groupCount() returns 3, which is then used to iterate through all captured groups.
Advantages of groupCount() Method
- Returns the total number of capturing groups in a regular expression.
- Helps process multiple regex groups dynamically using loops.
- Useful while parsing structured text such as emails, dates, and log files.
- Works efficiently with group(int) to retrieve captured values.
- Simplifies regex-based text extraction and validation.