Nested Groups and Group Numbering
What you'll learn: How Java numbers capturing groups when parentheses are nested inside each other.
The Core Idea
When you nest parentheses in a regular expression, Java assigns group numbers based on the position of each opening parenthesis as you read from left to right. This means outer groups get lower numbers, and inner groups get higher numbers — even if the inner group closes before the outer one.
Think of it like counting doors as you walk down a hallway: the first door you pass is #1, the second is #2, and so on — regardless of when you actually step through each door.
How Numbering Works
Given the pattern ((A)(B)):
- Group 1 =
((A)(B))— the outermost parentheses (opens first) - Group 2 =
(A)— opens second, nested inside group 1 - Group 3 =
(B)— opens third, also nested inside group 1
You count only opening parentheses, moving left to right through the pattern string.
Example
Pattern pattern = Pattern.compile("((\\d+)-(\\w+))");
Matcher matcher = pattern.matcher("Item: 123-abc");
if (matcher.find()) {
System.out.println("Group 0: " + matcher.group(0)); // 123-abc
System.out.println("Group 1: " + matcher.group(1)); // 123-abc
System.out.println("Group 2: " + matcher.group(2)); // 123
System.out.println("Group 3: " + matcher.group(3)); // abc
}
Here, group 1 captures the entire match inside the outer parentheses, while groups 2 and 3 capture the nested pieces (digits and word characters).
Key Takeaway: Nested groups are numbered by the left-to-right position of their opening parenthesis, allowing you to extract both composite values and their individual parts from the same match.