Skip to content

Use Getitem For Re Match Groups

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

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

Section titled “Sourcery refactoring id: use-getitem-for-re-match-groups”

Access groups in re.Match objects using getitem

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

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.