我正在尝试使用re.findall按顺序获取查询的开始和结束位置
@H_301_7@
@H_301_7@
import re sequence = 'aaabbbaaacccdddeeefff' query = 'aaa' findall = re.findall(query,sequence) >>> ['aaa','aaa']@H_301_7@我如何得到像findall.start()或findall.end()的东西? @H_301_7@我想得到 @H_301_7@
start = [0,6] end = [2,8]@H_301_7@我知道 @H_301_7@
search = re.search(query,sequence) print search.start(),search.end() >>> 0,2@H_301_7@只会给我第一个例子
解决方法
使用
re.finditer
:
@H_301_7@
@H_301_7@
>>> import re >>> sequence = 'aaabbbaaacccdddeeefff' >>> query = 'aaa' >>> r = re.compile(query) >>> [[m.start(),m.end()] for m in r.finditer(sequence)] [[0,3],[6,9]]@H_301_7@来自文档: @H_301_7@
@H_301_7@Return aniterator
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.