English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Matcher groupCount() method and example in Java

The java.util.regex.Matcher class represents an engine for executing various matching operations. This class has no constructor, and it can be usedmatches()The method of the java.util.regex.Pattern class creates/Get an instance of this class.

This (Matcher) classgroupCount()Method to calculate the number of capturing groups in the current match.

Example1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupTest {
   public static void main(String[] args) {
      String regex = "(.*);+);*
      String input = "This is a sample Text, 1234, with numbers in between.";
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Match the compiled pattern in the string
      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());
      }
   }
}

Output result

First group match: This is a sample Text, 123
Second group match: 4
Third group match: , with numbers in between.
Number of groups: 3

Example2

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> wherever <b>it</b>/b> alternative <b>word</b>/b> is <b>bold</b>/b></p>.";
      //Regular expression matches the content of the bold tag
      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 ";
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Match the compiled pattern in the string
      Matcher matcher = pattern.matcher(str);
      while (matcher.find()) {
         System.out.println(matcher.group(0));
      }
      System.out.println("Total capturing groups: ");+matcher.groupCount());
   }
}

Output result

tit
tat
tweet
tact
that
tilt
text
tart
Total capturing groups: 3