Question
Asked By – Greg
How can I get the start and end positions of all matches using the re
module? For example given the pattern r'[a-z]'
and the string 'a1b2c3d4'
I’d want to get the positions where it finds each letter. Ideally, I’d like to get the text of the match back too.
Now we will see solution for issue: Python Regex – How to Get Positions and Values of Matches
Answer
import re
p = re.compile("[a-z]")
for m in p.finditer('a1b2c3d4'):
print(m.start(), m.group())
This question is answered By – Peter Hoffmann
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0