正则表达式findall start()和end()?Python

前端之家收集整理的这篇文章主要介绍了正则表达式findall start()和end()?Python前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用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 an iterator yielding MatchObject 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.

猜你在找的正则表达式相关文章