我正在尝试使用 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]]
来自文档:
Return an
iterator
yieldingMatchObject
instances over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found.
关于python - 正则表达式 findall start() 和 end() ? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17604490/