Named groups in Python's re module allow you to assign a name to a capturing group, making it easier to reference the matched text by name rather than by number. This improves code readability and maintainability, especially in complex regular expressions.
Syntax
Use
(?P<name>pattern)to define a named group, wherenameis a valid Python identifier (e.g.,(?P<timestamp>\d+)).Reference the group using
match.group('name')or(?P=name)in the same regex for backreferences.
Example
import re
log = "[2025-06-09 14:23:01] INFO - OrderID: #A1B2C3, Customer: John Doe (CA), Total: $49.99"
pattern = r'\[(?P<timestamp>.*?)\] .*?OrderID: (?P<order_id>\#\w+), Customer: (?P<name>[A-Za-z ]+) $$(?P<state>\w{2})$$, Total: \$(?P<total>[0-9]+\.[0-9]{2})'
match = re.search(pattern, log)
if match:
print(match.group('timestamp')) # Output: 2025-06-09 14:23:01
print(match.group('order_id')) # Output: #A1B2C3
print(match.group('name')) # Output: John Doe
print(match.group('state')) # Output: CA
print(match.group('total')) # Output: 49.99Key Features
Named groups are also numbered: They can be accessed via both name and index (e.g.,
group(1)andgroup('name')).match.groupdict()returns a dictionary of all named groups and their matched values.Backreferences: Use
(?P=name)to match the same text captured by a named group (e.g.,(?P<word>\w+) \1matches repeated words).
Benefits
Readability: Code is self-documenting when group names describe their purpose.
Maintainability: Adding or removing groups doesn’t break existing code if you use names instead of numbers.
Consistency: Python’s
remodule was the first to introduce this feature, and it’s now widely supported across many regex flavors.
For more details, refer to the official Python re module documentation.
Videos
» pip install fastapi
Since we're all guessing, I might as well give mine: I've always thought it stood for Python. That may sound pretty stupid -- what, P for Python?! -- but in my defense, I vaguely remembered this thread [emphasis mine]:
Subject: Claiming (?P...) regex syntax extensions
From: Guido van Rossum ([email protected])
Date: Dec 10, 1997 3:36:19 pm
I have an unusual request for the Perl developers (those that develop the Perl language). I hope this (perl5-porters) is the right list. I am cc'ing the Python string-sig because it is the origin of most of the work I'm discussing here.
You are probably aware of Python. I am Python's creator; I am planning to release a next "major" version, Python 1.5, by the end of this year. I hope that Python and Perl can co-exist in years to come; cross-pollination can be good for both languages. (I believe Larry had a good look at Python when he added objects to Perl 5; O'Reilly publishes books about both languages.)
As you may know, Python 1.5 adds a new regular expression module that more closely matches Perl's syntax. We've tried to be as close to the Perl syntax as possible within Python's syntax. However, the regex syntax has some Python-specific extensions, which all begin with (?P . Currently there are two of them:
(?P<foo>...)Similar to regular grouping parentheses, but the text
matched by the group is accessible after the match has been performed, via the symbolic group name "foo".
(?P=foo)Matches the same string as that matched by the group named "foo". Equivalent to \1, \2, etc. except that the group is referred
to by name, not number.I hope that this Python-specific extension won't conflict with any future Perl extensions to the Perl regex syntax. If you have plans to use (?P, please let us know as soon as possible so we can resolve the conflict. Otherwise, it would be nice if the (?P syntax could be permanently reserved for Python-specific syntax extensions. (Is there some kind of registry of extensions?)
to which Larry Wall replied:
[...] There's no registry as of now--yours is the first request from outside perl5-porters, so it's a pretty low-bandwidth activity. (Sorry it was even lower last week--I was off in New York at Internet World.)
Anyway, as far as I'm concerned, you may certainly have 'P' with my blessing. (Obviously Perl doesn't need the 'P' at this point. :-) [...]
So I don't know what the original choice of P was motivated by -- pattern? placeholder? penguins? -- but you can understand why I've always associated it with Python. Which considering that (1) I don't like regular expressions and avoid them wherever possible, and (2) this thread happened fifteen years ago, is kind of odd.
Python Extension. From the Python Docs:
The solution chosen by the Perl developers was to use (?...) as the extension syntax. ? immediately after a parenthesis was a syntax error because the ? would have nothing to repeat, so this didn’t introduce any compatibility problems. The characters immediately after the ? indicate what extension is being used, so (?=foo) is one thing (a positive lookahead assertion) and (?:foo) is something else (a non-capturing group containing the subexpression foo).
Python supports several of Perl’s extensions and adds an extension syntax to Perl’s extension syntax.If the first character after the question mark is a P, you know that it’s an extension that’s specific to Python
https://docs.python.org/3/howto/regex.html