Python的re匹配对象在匹配对象上具有.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)。