In Python, the (?P<group_name>…)
syntax allows one to refer to the matched string through its name:
>>> import re
>>> match = re.search('(?P<name>.*) (?P<phone>.*)', 'John 123456')
>>> match.group('name')
'John'
What does "P" stand for? I could not find any hint in the official documentation.
I would love to get ideas about how to help my students remember this syntax. Knowing what "P" does stand for (or might stand for) would be useful.
This question is related to
python
regex
regex-group
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
Pattern! The group names a (sub)pattern for later use in the regex. See the documentation here for details about how such groups are used.
Source: Stackoverflow.com