Working with simple groups in Java Regular Expressions

Multiple characters can be treated as a single unit using groups 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.

A program that demonstrates groups 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("I am f9");
System.out.println("The input string is: I am f9");
System.out.println("The Regex is: \w\d");
System.out.println();
if (m.find()) {
System.out.println("Match: " + m.group());
}
}
}

The output of the above program is as follows −

The input string is: I am f9
The Regex is: \w\d
Match: f9

Now let us understand the above program.

The subsequence “\w\d” is searched in the string sequence "I am f9". 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("I am f9");
System.out.println("The input string is: I am f9");
System.out.println("The Regex is: \w\d");
System.out.println();
if (m.find()) {
System.out.println("Match: " + m.group());
}
Vikyath Ram

A born rival