我想在正则表达式的匹配中获取组的索引。注意下图:
您可以看到它创建了 3 个匹配项。左侧显示比赛的索引和组 1 的索引。我想在Python中获取Group 1的索引,我该怎么做?下面的图片显示了 Python 的返回结果:
您需要传递一个参数来i.span()指定要查找范围的组(否则,它只是默认为整个匹配)。像这样:
import re
s = 'aaadaa'
matches = re.finditer(r'(?<=(aa))', s)
for i in matches:
print(i.span(1))
# This will work since you only have one capturing group, but if you have more than one you may have to make separate calls to .span()
Run Code Online (Sandbox Code Playgroud)