簡體   English   中英

Python正則表達式,匹配組范圍(開始和結束)

[英]Python regex, match group span (start and end)

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

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)

例如,在這種情況下,我只需要匹配'car'的范圍而不是整個語句。

你需要傳遞span參數:

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

1表示第一組,默認為零 - 表示整個匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM