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.
Run Code Online (Sandbox Code Playgroud)
上面的预期输出是 (7, 10)
小智 2
您可以提供Match.start( 和Match.end) 组名称来获取组的开始(结束)位置:
>>> import re
>>> REGEX = re.compile(r'h(?P<num>[0-9]{3})p')
>>> test = "hello h889p something"
>>> match = REGEX.search(test)
>>> match.start('num')
7
>>> match.end('num')
10
Run Code Online (Sandbox Code Playgroud)
与其他答案中建议的使用方法相比,这种方法的优点str.index是,如果组字符串多次出现,您不会遇到问题。