How can I find the span of a inside group by regex? I have the following code, but I don't know how to get the span (start, end) of the matched group inside the parentheses:
statement = r'new (car)|old (car)'
text = 'I bought a new car and got rid of the old car'
match = re.search(statement, text)
match.span()
Out: (11, 18)
for match in re.finditer(statement, text):
print match.span()
Out: (11, 18)
Out: (38, 45)
In this case for example, I only need to match the span of the 'car' not the whole statement.
You need to pass span
an argument:
for match in re.finditer(statement, text):
print match.span(1)
1 is referring to the first group, the default is zero - which means the whole match.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With