Java Matcher group() Method
Example
Find a date in a text, and print the whole match and each group:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
Matcher matcher = pattern.matcher("Java 8 was released on 2014-03-18.");
if (matcher.find()) {
System.out.println(matcher.group());
System.out.println("Year: " + matcher.group(1));
System.out.println("Month: " + matcher.group(2));
System.out.println("Day: " + matcher.group(3));
}
}
}
Definition and Usage
The group() method returns the text that was found by the last match.
A group is a part of the pattern inside parentheses ( ). group(1) returns the text that matched the first group, group(2) the second group, and so on. group() and group(0) return the whole match.
Note: In the pattern, \d means one digit, and {4} means exactly 4 times. So \d{4} matches 4 digits, like 2014. In a Java string, you must write the backslash two times: "\\d{4}".
Syntax
One of the following:
public String group()
public String group(int group)
public String group(String name)
Parameter Values
| Parameter | Description |
|---|---|
| group | Optional. The number of the group. Groups are numbered from left to right by their opening parenthesis, starting at 1. 0 means the whole match. |
| name | Optional. The name of a named group. A named group is written as (?<name>X) in the pattern. |
Technical Details
| Returns: | The text that matched, as a String, or null if the group did not match any text. |
|---|---|
| Throws: | IllegalStateException - if no match has been found. IndexOutOfBoundsException - if there is no group with the given number. |
Related Pages
❮ RegEx Methods