Skip to content

Use Getitem For Re Match Groups

Sourcery refactoring id: use-getitem-for-re-match-groups

Description

Access groups in re.Match objects using getitem

Before

m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
entire = m.group(0)  # The entire match
first = m.group(1)  # The first parenthesized subgroup.

After

m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
entire = m[0]  # The entire match
first = m[1]  # The first parenthesized subgroup.

Explanation

In Python 3.6 the ability to access groups from a match using __getitem__ was introduced. This is slightly shorter, and once you've understood that it is possible, easier to read and understand.