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

Capturing Groups — Pulling Values Out

~8 min · capture, extraction

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

Numbered slots, left to right

Every capturing group gets a number based on the position of its OPENING parenthesis, counted left to right. Group 0 is always the entire match.

Pattern (\d{4})-(\d{2})-(\d{2}) against 2026-05-04:

  • Group 0: 2026-05-04 (whole match)
  • Group 1: 2026
  • Group 2: 05
  • Group 3: 04

Accessing groups

Most languages give you direct access to numbered groups:

  • Python: m.group(1), m.groups() for tuple of all
  • JavaScript: match[1], match[2]...
  • Go: m[1], m[2]...
  • ripgrep: $1, $2 in --replace mode

The findall surprise

Python's re.findall behaves quirkily with groups: when there are NO groups, it returns full matches; when there's ONE group, it returns just that group; when there are MULTIPLE groups, it returns tuples. Don't try to be clever — use re.finditer for predictable group access.

Code

Working with capturing groups·python
import re

# Date parsing
pattern = r'(\d{4})-(\d{2})-(\d{2})'
m = re.match(pattern, '2026-05-04')
print(m.group())     # full match
# '2026-05-04'
print(m.group(1))    # year
# '2026'
print(m.groups())    # all groups as tuple
# ('2026', '05', '04')

# findall behavior with groups
re.findall(r'(\d+)-(\d+)', '12-34 56-78')
# [('12', '34'), ('56', '78')]  — tuples per match

# finditer is more predictable
for m in re.finditer(r'(\d+)-(\d+)', '12-34 56-78'):
    print(m.group(1), m.group(2))
# 12 34
# 56 78

External links

Exercise

Write a pattern that extracts the order ID, customer name, and total from a line like ORDER #1138 — Pippa — $42.00. Use three capturing groups. Verify with m.groups() returns the three pieces in order.

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.