Role of Matcher.group() method in Java Regular Expressions


The method java.time.Matcher.group() is used to find the subsequence in the input sequence string that is a match to the required pattern. This method returns the subsequence that is matched by the previous match which can even be empty.

A program that demonstrates the method Matcher.group() in Java regular expressions is given as follows:

Example

 Live Demo

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("\\w\\d");
      Matcher m = p.matcher("This is gr8");
      System.out.println("The input string is: This is gr8");
      System.out.println("The Regex is: \\w\\d");
      System.out.println();
      if (m.find()) {
         System.out.println("Match: " + m.group());
      }
   }
}

Output

The input string is: This is gr8
The Regex is: \w\d
Match: r8

Now let us understand the above program.

The subsequence “\\w\\d” is searched in the string sequence "This is gr8". The find() method is used to find if the subsequence is in the input sequence and the required result is printed using the group() method. A code snippet which demonstrates this is as follows:

Pattern p = Pattern.compile("\\w\\d");
Matcher m = p.matcher("This is gr8");
System.out.println("The input string is: This is gr8");
System.out.println("The Regex is: \\w\\d");
System.out.println();
if (m.find()) {
   System.out.println("Match: " + m.group());
}
raja
Published on 12-Feb-2019 15:07:08
Advertisements