Capturing Groups and Group Numbers
You'll learn how Java numbers capturing groups in a regular expression and how to retrieve their content using Matcher methods.
How Group Numbering Works
When you create capturing groups in a regular expression using parentheses (), Java automatically assigns each group a number starting from 1. The entire match itself is always group 0. Groups are numbered from left to right based on the position of their opening parenthesis.
For example, in the pattern "(\\w+)@(\\w+\\.\\w+)":
- Group 0: the entire match (e.g.,
"user@example.com") - Group 1:
(\\w+)— the username part - Group 2:
(\\w+\\.\\w+)— the domain part
Accessing Groups with Matcher Methods
Once you've called find() or matches() successfully on a Matcher, you can retrieve captured groups:
Pattern pattern = Pattern.compile("(\\w+)@(\\w+\\.\\w+)");
Matcher matcher = pattern.matcher("john@example.com");
if (matcher.matches()) {
String fullMatch = matcher.group(0); // "john@example.com"
String username = matcher.group(1); // "john"
String domain = matcher.group(2); // "example.com"
}
The group(int) method takes the group number as its argument. Calling group() with no arguments is equivalent to group(0) — it returns the entire match.
Think of groups like labeled boxes: group 0 is the entire package, and groups 1, 2, 3, etc. are individual items inside, numbered by the order they appear in your pattern.
Key Takeaway: Capturing groups are numbered from 1 based on their opening parenthesis position in the pattern, with group 0 always representing the entire match; use matcher.group(n) to retrieve the content of group n after a successful match.