Named capture groups in Python
Labeling the parts of a match for readable extraction.
import re
pattern = re.compile(
r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})")
m = pattern.search("released on 2026-07-29, patched later")
year = m.group("year")
month, day = m.group("month", "day")
parts = m.groupdict()
dates = pattern.findall("2025-01-01 then 2026-07-29")
for year, month, day in dates:
print(f"{day}/{month}/{year}")
How it works
(?P<year>...)names a capture group.group('year')andgroupdictread them back.findallreturns tuples for multi-group patterns.
Keywords and builtins used here
forprint
The run, in numbers
- Lines
- 13
- Characters to type
- 344
- Tokens
- 104
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 59 seconds.
Step 2 of 5 in Regular expressions, step 2 of 41 in Domain tools.