What is the group() function of the Matcher class in Java?
The group() function of the Java Matcher class is used to return the specific substring that matches the most recent match operation. The java.util.regex package contains the Matcher class, which compares texts to regular expressions.
Syntax
There are two versions of the group() function:
public String group()
In this case, the full substring that fits the pattern is returned. It is the same as group (0).
public String group(int group)
This version gives the matching substring for the given capturing group. The brackets in the regular expression pattern define the capturing group.
Code example
import java.util.regex.Matcher;import java.util.regex.Pattern;public class Test {public static void main(String[] args) {String input = "Hello, my name is John Doe. I am 82 years old.";Pattern pattern = Pattern.compile("name is ([A-Za-z ]+)\\. I am ([0-9]+) years old\\.");Matcher matcher = pattern.matcher(input);if (matcher.find()) {String fullName = matcher.group(1);String age = matcher.group(2);System.out.println("Full Name: " + fullName);System.out.println("Age: " + age);}}}
Explanation
-
Lines 1–2: We use these import lines to import the
PatternandMatcherclasses into Java from thejava.util.regexpackage, which supports regular expressions. -
Lines 4–5: We define the
Testclass. Java program’smainmethod is used as its entry point. -
Line 6: We define the
Stringtype variableinputand assign it a string value. It is an example of the input text that will be compared to the regular expression pattern. -
Line 8: We compile the input string using the
Pattern.compile()function by creating an objectpatternof thePatternclass. The regular expression"name is ([A-Za-z ]+).+([0-26]+) years old"is used to construct the pattern. -
Line 10: We use the
matcher()function of thepatternobject to build aMatcherclass object and we name itmatcher. Using a regular expression pattern, matching operations are carried out on the input string using thematcherobject. -
Line 12: We check if a match is found within the input string.
-
Lines 14–15: We use the
group()function of thematcherobject to extract the matched substrings if a match is found.group(1)returns the substring that corresponds to the first capturing group (the name), andgroup(2)returns the substring that corresponds to the second capturing group (the age). -
Lines 17–18: We print the returned value of the variables
fullNameandageto the console.
Conclusion
We can efficiently use regular expressions to extract and process specified substrings from input text in Java by understanding and employing the group() function of the Matcher class.
Free Resources