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

标签 python regex sequence findall

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

相关文章:

python - 属性错误 : module 'alembic.context' has no attribute 'config'

java - 如何自动或实用地将 java 代码块替换为另一个代码块?

r - 从 'A' -'Z' 生成字符序列

Python 序列命名约定

python - 生成一个列表 a(n) 不是 prime + a(k), k < n 的形式

python - 在 Python 中自动化 Selenium 测试

python - Wasserstein GAN 的训练稳定性

Python 不直观的成员变量行为

regex - 替换 re.findall() 结果中的部分字符串

javascript - 如何以更有效的方式将标题添加到 csv 文件