Matcher group() method in Java with Examples

JavaObject Oriented ProgrammingProgramming

The java.util.regex.Matcher class represents an engine that performs various match operations. There is no constructor for this class, you can create/obtain an object of this class using the matches() method of the class java.util.regex.Pattern.

The group() method of this (Matcher) class returns the matched input subsequence during the last match.

Example 1

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> an <b>example</b> HTML <b>script</b> "
         + "where <b>every</b> alternative <b>word</b> is <b>bold</b>. "
         + "It <i>also</i> contains <i>italic</i> words</p>";
      //Regular expression to match contents of the bold tags
      String regex = "<b>(\\S+)</b>|<i>(\\S+)</i>";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(str);
      while (matcher.find()) {
         System.out.println(matcher.group());
      }
   }
}

Output

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

Another variant of this method accepts an integer variable representing the group, where the captured groups are indexed starting from 1 (left to right).

Example 2

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

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.
raja
Published on 20-Nov-2019 06:46:07
Advertisements