Tutorialspoint

1 Answer
Jai Janardhan

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());
}

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.