Chapter 7: Groups

Named groups

face Josiah Wang

You can also assign a name/identifier to each of your group. You can then access your groups by their name. This is done with (?P<name> ). Note that name must be a valid Python identifier.

The names make the groups more semantically meaningful, rather than having to refer to them by a number.

As usual, try out the examples yourself and make sure you understand what each line is doing (should be self-explanatory). Consult the documentation if you have doubts.

>>> pattern = "Name: (?P<name>[A-Za-z ]+); Phone: (?P<phone>\d+)"
>>> string = "Name: Josiah Wang; Phone: 012345678"
>>> match = re.match(pattern, string)
>>> print(match)
<re.Match object; span=(0, 35), match='Name: Josiah Wang; Phone: 012345678'>
>>> match.group("name")
'Josiah Wang'
>>> match.group("phone")
'012345678'
>>> match.group(1)
'Josiah Wang'
>>> match.group(2)
'012345678'
>>> match.groupdict()
{'name': 'Josiah Wang', 'phone': '012345678'}