Make use of regular expressions more readable with named groups.
m.group(2)
'Mackenzie'
m.group('first_name')
'Mackenzie'
The Zen of Python, by Tim Peters
Readability counts.
import re
Regular expressions can be used to indicate if a string matches a pattern or not.
Regular expressions can also be used to do some parsing. The substrings of interest are called groups. The traditional way of referring to a group is by index number. Python has another way of referring to a group by name.
Using names give both the regular expression and references to match groups more meaning. They make Python code more readable.
foo_pattern = re.compile('''
^
([A-Za-z]+)
,[ ]
([A-Za-z]+)
$
''', re.VERBOSE)
s = 'James, Mackenzie'
m = re.match(foo_pattern, s)
m
<_sre.SRE_Match object; span=(0, 16), match='James, Mackenzie'>
m.groups
<function SRE_Match.groups>
m.group(0)
'James, Mackenzie'
m.group(1)
'James'
m.group(2)
'Mackenzie'
foo_pattern = re.compile('''
^
(?P<last_name>[A-Za-z]+)
,[ ]
(?P<first_name>[A-Za-z]+)
$
''', re.VERBOSE)
m = re.match(foo_pattern, s)
m
<_sre.SRE_Match object; span=(0, 16), match='James, Mackenzie'>
m.groups
<function SRE_Match.groups>
m.group(0)
'James, Mackenzie'
m.group(1)
'James'
m.group(2)
'Mackenzie'
m.group('last_name')
'James'
m.group('first_name')
'Mackenzie'
Questions
first to name groups in regular expressions?
Eric found Named regular expression group “(?P<group_name>regexp)”: what does “P” stand for? article, which addresses both questions.