在单词中匹配多个双字符 - Python正则表达式

4
我想要识别具有两组双字母的单词(在字典结构中)。
我是Python/正则表达式新手,但已经从该网站上的一些类似问题中拼凑了几乎能用的代码。但还不够完美。
它只会捕获两个相同字母的重复部分,并且只会在它们被分开时才会捕获它们。我认为第二个\1的使用是问题所在,仅适用于与第一个捕获组相同字母的情况。通过regex101确认了这一点,但不确定如何调整正则表达式以正确匹配。
任何有关我偏离正道的指针都将不胜感激。
#logic being [any letter]* [any letter repeated] [any letter]* [any letter repeated] [any letter]* 

import json
import re

dict_data = {"hello":0, "aaoo":0, "aabaa":0, "aaaba":0, "bookkeeping":0, "bookkeeooping":0}
for key in dict_data:
    if re.search(r'\b.*(.)\1.*(.)\1.*\b', key):
        print("Match found: ", key)
    else:
        print("No match:    ", key)

输出结果为:

No match:     hello
No match:     aaoo          #This should work but doesn't
Match found:  aabaa         #This works
Match found:  aaaba         #This shouldn't, assume it is matching either 2nd&3rd a or 3rd&4th a
No match:     bookkeeping   #This should match but doesn't
Match found:  bookkeeooping #This works, assume it is matching oo twice
1个回答

3
第二个\1指的是第一个捕获组的值,而你需要引用第二个组的值,请使用\2re.search在输入字符串中搜索正则表达式匹配项,你不需要在输入的两端都使用.*
使用:
dict_data = {"hello":0, "aaoo":0, "aabaa":0, "aaaba":0, "bookkeeping":0, "bookkeeooping":0}
for key in dict_data:
    if re.search(r'(.)\1.*(.)\2', key):
        print("Match found: ", key)
    else:
        print("No match:    ", key)

查看Python示例演示结果。

No match:     hello
Match found:  aaoo
Match found:  aabaa
No match:     aaaba
Match found:  bookkeeping
Match found:  bookkeeooping

非常感谢,那很有道理 - 我以为1是指重复的次数,但现在明白了。 - Chris112
1
抱歉,Wiktor,新手错误。我在两个浏览器窗口中打开了这个问题,当我在第二个窗口点击回答时,可能取消了第一个窗口的回答。这是一个非常有帮助的答案! - Chris112
@Chris112 我明白了,没问题 :) - Wiktor Stribiżew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接