C.W.K.
Stream
Lesson 09 of 12 · published

Nested Groups

~6 min · nested, numbering

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

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.

Code

Nested groups·python
import re

# Outer captures the whole thing, inner captures pieces
m = re.match(r'((\d+)-(\d+))', '42-1138')
m.group(0)  # '42-1138' (full match)
m.group(1)  # '42-1138' (outer)
m.group(2)  # '42'
m.group(3)  # '1138'

# Numbering follows opening paren order
m = re.match(r'(a(b)c)(d)', 'abcd')
m.group(1)  # 'abc'
m.group(2)  # 'b'
m.group(3)  # 'd'

# Named groups survive nesting clearly
DATE = re.compile(r'(?P<full>(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2}))')
m = DATE.match('2026-05-04')
m.group('full')   # '2026-05-04'
m.group('year')   # '2026'
m.group('month')  # '05'
m.group('day')    # '04'

External links

Exercise

Write a pattern that captures a full email address in group 1 and the domain alone in group 2. The outer group wraps the inner local-part + @ + domain pattern. Test that m.group(1) gives the whole email and m.group(2) gives just the domain.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.