Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
groupint / StringThe 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/14

Named 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 -> 8080

Notes

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

In the tutorial

  • Regular expressions — Regular expressions in Java: matches, replaceAll, splitting by a pattern, the Pattern and Matcher classes, groups and escaping backslashes.

Thanks for reading!

Donate to the site — we work hard for you.