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

2024-04-19 12:04:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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)


Tags: ofthe对象intestreindexmatch
3条回答

您可以只使用字符串索引和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)

注意:作为Tom pointed out,您可能需要考虑使用^ {CD2>},以防止可能来自字符串具有相同字符的错误。例如,如果数字是899,那么results将是(7, 8),因为9的第一个实例位于索引8处

给定示例的解决方案可以是使用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'>

the existing answer的一个轻微修改是使用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"包围)

相关问题 更多 >