SyntaxStudy
Sign Up
Python Named Capturing Groups
Python Intermediate 4 min read

Named Capturing Groups

Named Groups

Use (?P<name>...) to give groups names. Access them with match.group("name") or match.groupdict().

Example
import re

pattern = r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})"
m = re.search(pattern, "2024-07-15")
print(m.group("year"))   # 2024
print(m.groupdict())     # {"year": "2024", "month": "07", "day": "15"}
Pro Tip

Named groups make your regex self-documenting.