gpt4 book ai didi

Python重新查找组匹配的开始和结束索引

转载 作者:行者123 更新时间:2023-12-04 16:24:46 29 4
gpt4 key购买 nike

Python 的重新匹配对象在匹配对象上有 .start() 和 .end() 方法。我想找到小组赛的开始和结束索引。我怎样才能做到这一点?示例:

>>> import re
>>> REGEX = re.compile(r'h(?P<num>[0-9]{3})p')
>>> test = "hello h889p something"
>>> match = REGEX.search(test)
>>> match.group('num')
'889'
>>> match.start()
6
>>> match.end()
11
>>> match.group('num').start() # just trying this. Didn't work
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'start'
>>> REGEX.groupindex
mappingproxy({'num': 1}) # this is the index of the group in the regex, not the index of the group match, so not what I'm looking for.

上面的预期输出是 (7, 10)

最佳答案

给定示例的解决方法可能是使用lookarounds:

import re
REGEX = re.compile(r'(?<=h)[0-9]{3}(?=p)')
test = "hello h889p something"
match = REGEX.search(test)
print(match)

输出

<re.Match object; span=(7, 10), match='889'>

关于Python重新查找组匹配的开始和结束索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67047196/

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