The groupCount() method of the MatchResult interface returns the number of capturing groups defined in a regular expression. It counts only the groups enclosed within parentheses () and does not include the entire matched pattern.
- Counts only groups enclosed in parentheses ().
- Does not count the complete match as a group.
- Returns an integer value.
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("(Java)(Programming)");
Matcher matcher = pattern.matcher("JavaProgramming");
System.out.println("Number of Groups: " + matcher.groupCount());
}
}
Output
Number of Groups: 2
Explanation: The regular expression contains two capturing groups: (Java) and (Programming). Therefore, groupCount() returns 2.
Syntax
public int groupCount()
- Parameters: This method do not takes any parameter.
- Returns: An
intrepresenting the total number of capturing groups in the regular expression.
Example 1: Java code to illustrate groupCount() method
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
// Get the regex to be checked
String regex = "(Geeks)";
// Create a pattern from regex
Pattern pattern
= Pattern.compile(regex);
// Get the String to be matched
String stringToBeMatched
= " GeeksForGeeks Geeks for For Geeks Geek";
// Create a matcher for the input String
MatchResult matcher
= pattern
.matcher(stringToBeMatched);
// Get the number of capturing groups
// using groupCount() method
System.out.println(matcher.groupCount());
}
}
Output
1
Explanation: The regular expression contains one capturing group (Geeks). Hence, the groupCount() method returns 1.
Example 2
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
// Get the regex to be checked
String regex = "GFG";
// Create a pattern from regex
Pattern pattern
= Pattern.compile(regex);
// Get the String to be matched
String stringToBeMatched
= "FGF GF FG FGF";
// Create a matcher for the input String
MatchResult matcher
= pattern
.matcher(stringToBeMatched);
// Get the number of capturing groups
// using groupCount() method
System.out.println(matcher.groupCount());
}
}
Output
0
Explanation: The regular expression GFG does not contain any parentheses (), so there are no capturing groups. Therefore, groupCount() returns 0.