Numbered groups are fragile, named groups are stable
When your pattern grows, group numbers shift every time you add or remove parens. Named groups solve this by giving each capture a name you reference instead of a number.
Syntax varies by flavor:
- Python / older PCRE:
(?P<name>...) - .NET / PCRE / JavaScript:
(?<name>...) - Backreference to named group (Python):
(?P=name) - Backreference to named group (.NET / PCRE):
\k<name>
Python supports BOTH the (?P<name>...) form (its own) AND (?<name>...) as of 3.x. Cross-language, prefer the bare angle-bracket form when possible.
Why use named groups
Three reasons:
- Readable callers.
m.group('year')is self-documenting;m.group(1)requires comments. - Stable across edits. Adding a group in the middle doesn't break
m.group('year'). - Self-documenting patterns. Future-you reads
(?P<email>...)and knows what's being captured.
The cost
None worth mentioning. Named groups are free. Use them whenever a group's purpose isn't obvious from position.