Groups inside groups
Groups can nest. The outer group captures everything inside it; inner groups capture their pieces independently.
Pattern ((\d+)-(\d+)) against 42-1138:
- Group 1:
42-1138(the outer wraps everything) - Group 2:
42(first inner) - Group 3:
1138(second inner)
Numbering follows opening parens
Whichever ( appears first in left-to-right order gets the next group number. So in (a(b)c)(d):
- Group 1:
(a(b)c)— its(is leftmost - Group 2:
(b)— its(is second - Group 3:
(d)— its(is third
Use named groups to escape numbering hell
For deeply nested patterns, named groups save you. Edit the pattern, add or remove a group, and named references still work. Numbered references would all need updating.