MatchResult group(int group) method in Java with examples.


The java.util.regex.MatcheResult interface provides methods to retrieve the results of a match

You can get an object of this interface using the toMatchResult() method of the Matcher class. This method returns a MatchResult object which represents the match state of the current matcher.

The group(int group) method of this interface accepts an integer value representing a particular group and returns a string value representing the matched substring from the given input sequence, in the specified group during the last match.

Example

 Live Demo

import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupExample {
   public static void main( String args[] ) {
      String regex = "(.*)(\d+)(.*)";
      //Reading input from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      //Instantiating the Pattern class
      Pattern pattern = Pattern.compile(regex);
      //Instantiating the Matcher class
      Matcher matcher = pattern.matcher(input);
      //verifying whether a match occurred
      if(matcher.find()) {
         System.out.println("Match found");
      }
      MatchResult res = matcher.toMatchResult();
      String matchedData = res.group(2);
      System.out.println(matchedData);
   }
}

Output

Enter input text:
This is a sample Text, 123
Match found
3

Updated on: 10-Jan-2020

117 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements