Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex, match group span (start and end)

Tags:

python

regex

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.

like image 268
CentAu Avatar asked Oct 18 '15 12:10

CentAu


1 Answers

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.

like image 163
Maroun Avatar answered Oct 21 '22 22:10

Maroun