[英]Regex findall start() and end() ? Python
我正在嘗試使用re.findall按順序獲取查詢的開始和結束位置
import re
sequence = 'aaabbbaaacccdddeeefff'
query = 'aaa'
findall = re.findall(query,sequence)
>>> ['aaa','aaa']
我如何得到像findall.start()或findall.end()的東西?
我想得到
start = [0,6]
end = [2,8]
我知道
search = re.search(query,sequence)
print search.start(),search.end()
>>> 0,2
只會給我第一個例子
使用re.finditer
:
>>> import re
>>> sequence = 'aaabbbaaacccdddeeefff'
>>> query = 'aaa'
>>> r = re.compile(query)
>>> [[m.start(),m.end()] for m in r.finditer(sequence)]
[[0, 3], [6, 9]]
來自文檔:
返回一個
iterator
在字符串中的RE模式的所有非重疊匹配上產生MatchObject
實例。 從左到右掃描字符串,並按找到的順序返回匹配項。
你不能。 findall
是一個便利函數,正如文檔所說,返回“字符串列表”。 如果需要MatchObject
列表,則不能使用findall
。
但是,您可以使用finditer
。 如果你只是for match in re.findall(…):
迭代匹配for match in re.findall(…):
,你可以用for match in re.finditer(…)
的for match in re.finditer(…)
方式相同 - 除了你獲得MatchObject
值而不是字符串。 如果你確實需要一個列表,只需使用matches = list(re.finditer(…))
。
使用finditer而不是findall。 這會讓你返回一個產生MatchObject實例的迭代器,你可以從MatchObject獲得開始/結束。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.