2015-10-18 93 views
2

如何通過正則表達式找到內部組的跨度? 我有下面的代碼,但我不知道怎麼去匹配組的跨度(開始,結束)括號內:Python正則表達式,匹配組跨度(開始和結束)

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) 

在這種情況下,例如,我只需要搭配「汽車」的整個範圍並非整個說法。

回答

7

您必須通過span參數:

for match in re.finditer(statement, text): 
    print match.span(1) 

1參照第一組,所述默認值是零 - 這意味着整個的匹配。

相關問題