正则表达式反向引用 findall 不起作用

oll*_*bbs 3 python regex backreference findall python-3.x

我最近在程序中使用正则表达式。在这个程序中,我使用它们在单词列表中查找与某个 RE 匹配的单词。然而,当我尝试使用这个程序进行反向引用时,我得到了一个有趣的结果。

这是代码:

import re
pattern = re.compile(r"[abcgr]([a-z])\1[ldc]")
string = "reel reed have that with this they"
print(re.findall(pattern, string))
Run Code Online (Sandbox Code Playgroud)

我期望的是结果(当我将它与Pythex["reel","reed"]一起使用时,正则表达式与这些匹配)

但是,当我使用 python 运行代码(我使用 3.5.1)时,我得到以下结果:

['e','e']

请对 RE 有更多经验的人解释一下为什么我会遇到这个问题以及我可以采取什么措施来解决它。

谢谢。

Wik*_*żew 5

唯一返回使用正则表达式模式内的捕获组re.findall捕获的捕获值。

使用re.finditer它将保留第零组(整场比赛):

import re
p = re.compile(r'[abcgr]([a-z])\1[ldc]')
s = "reel reed have that with this they"
print([x.group(0) for x  in p.finditer(s)])
Run Code Online (Sandbox Code Playgroud)

查看IDEONE 演示