Matcher.group()
Returns the text of the current match or of one of its parenthesized groups.
Available since: Java 1.4
Syntax
public String group(int group)Parameters
| Parameter | Type | Description |
|---|---|---|
| group | int / String | The group number (0 is the whole match, 1 the first parentheses) or a group name. Without an argument, the whole match. |
Return value
StringThe group text, or null if the group did not take part in the match.
Examples
Numbered groups — parts of a date:
void main() {
Matcher m = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})").matcher("Due: 2025-03-14");
if (m.find()) {
IO.println(m.group());
IO.println(m.group(1));
IO.println(m.group(2) + "/" + m.group(3));
}
}Output:
2025-03-14
2025
03/14Named groups (?<name>...) are easier to read:
void main() {
Pattern p = Pattern.compile("(?<key>\\w+)=(?<value>\\w+)");
Matcher m = p.matcher("host=localhost port=8080");
while (m.find()) {
IO.println(m.group("key") + " -> " + m.group("value"));
}
}Output:
host -> localhost
port -> 8080Notes
group() can only be called after a successful find() or matches(), otherwise you get IllegalStateException: No match found. Groups are numbered by their opening parentheses from left to right. Parentheses used only for grouping, without capturing, are written as (?:...).
See also
- Matcher.find() — Searches for the next match of the pattern anywhere in the string.
- Matcher.matches() — Checks whether the whole string matches the pattern.
- String.replaceAll() — Replaces every match of a regular expression.
In the tutorial
- Regular expressions — Regular expressions in Java: matches, replaceAll, splitting by a pattern, the Pattern and Matcher classes, groups and escaping backslashes.