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

Matcher group() 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 can be usedmatches()The method of the java.util.regex.Pattern class creates/Get an object of this class.

This (Matcher) classgroup()The method returns the matched input subsequence during the last match.

Example1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupExample {
   public static void main(String[] args) {
      String str = "<p>This <b>is</b>/<b>an</b> <b>example</b>/<b>HTML</b> <b>script</b>/<b> </b>
         + "where <b>every</b>/<b>alternative</b> <b>word</b>/<b>is</b> <b>bold</b>/<b>is</b> "
         + "It <i>also</i>/i>contains</i><i>italic</i>/i>words</i>/p>";
      //Regular expressions are used to match the content of bold tags
      String regex = "<b>(\S+);/b>|<i>(\S+);/i>";
      //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());
      }
   }
}

Output Result

<b>is</b>/b>
<b>example</b>/b>
<b>script</b>/b>
<b>every</b>/b>
<b>word</b>/b>
<b>bold</b>/b>
<i>also</i>/i>
<i>italic</i>/i>

Another variant of this method accepts an integer variable representing the group, where the captured group is from1(From left to right) starting index.

Example2

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("match: ",+matcher.group(0));
         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));
      }
   }
}

Output Result

match: This is a sample Text, 1234, with numbers in between.
First group match: This is a sample Text, 123
Second group match: 4
Third group match: , with numbers in between.