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

Python re find start and end index of group match

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() 方法:

>>> import re
>>> REGEX = re.compile(r'h(?P<num>[0-9]{3})p')
>>> test = "hello h889p something"
>>> match = REGEX.search(test)
>>> test.index(match.group('num')[0])
7
>>> test.index(match.group('num')[-1])
9

如果您希望将结果作为元组:

>>> str_match = match.group("num")
>>> results = (test.index(str_match[0]), test.index(str_match[-1]))
>>> results
(7, 9)

注意:与 一样,您可能要考虑使用 results = (test.index(str_match), text.index(str_match)+len(str_match)) 以防止可能因字符串具有相同字符而引起的错误。例如,如果数字是 899,那么 results 将是 (7, 8),因为 9 的第一个实例位于索引 8。

的一个细微修改是使用 index 来查找整个组,而不是组的开始和结束字符:

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

# modification here to find the start point
idx = test.index(group)

# find the end point using len of group
output = (idx, idx + len(group)) #(7, 10)

这会在确定索引时检查整个字符串 "889"。因此,与检查第一个 8 和第一个 9 相比,出错的可能性要小一些,尽管它仍然不完美(即,如果 "889" 出现在字符串的较早位置,而不是被包围通过 "h""p").

给定示例的解决方法是使用环视:

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'>