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)
您可以只使用字符串索引和
index()
方法:如果要将结果作为元组,请执行以下操作:
注意:作为Tom pointed out,您可能需要考虑使用^ {CD2>},以防止可能来自字符串具有相同字符的错误。例如,如果数字是
899
,那么results
将是(7, 8)
,因为9
的第一个实例位于索引8处给定示例的解决方案可以是使用lookarounds:
输出
对the existing answer的一个轻微修改是使用
index
查找整个组,而不是组的起始字符和结束字符:这将在确定索引时检查整个字符串
"889"
。因此,检查第一个8
和第一个9
时出错的可能性较小,尽管它仍然不是完美的(即如果"889"
出现在字符串的前面,而不是被"h"
和"p"
包围)相关问题 更多 >
编程相关推荐