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.
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.
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);}}}
Lines 1–2: We use these import lines to import the Pattern
and Matcher
classes into Java from the java.util.regex
package, which supports regular expressions.
Lines 4–5: We define the Test
class. Java program’s main
method is used as its entry point.
Line 6: We define the String
type variable input
and 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 object pattern
of the Pattern
class. 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 the pattern
object to build a Matcher
class object and we name it matcher
. Using a regular expression pattern, matching operations are carried out on the input string using the matcher
object.
Line 12: We check if a match is found within the input string.
Lines 14–15: We use the group()
function of the matcher
object to extract the matched substrings if a match is found. group(1)
returns the substring that corresponds to the first capturing group (the name), and group(2)
returns the substring that corresponds to the second capturing group (the age).
Lines 17–18: We print the returned value of the variables fullName
and age
to the console.
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