gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:42:54 24 4
gpt4 key购买 nike

我正在尝试使用 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 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.

关于python - 正则表达式 findall start() 和 end() ? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17604490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com