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”Description
Section titled “Description”Access groups in
re.Match objects
using getitem
Before
Section titled “Before”m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")entire = m.group(0) # The entire matchfirst = m.group(1) # The first parenthesized subgroup.m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")entire = m[0] # The entire matchfirst = m[1] # The first parenthesized subgroup.Explanation
Section titled “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.