Python 用于删除重复字符和组合的正则表达式

Python 用于删除重复字符和组合的正则表达式,python,regex,string,duplicates,Python,Regex,String,Duplicates,我有一个字符串,它由在末尾有重复字符的单词组成。 这些字符可以是这样的组合: wordxxxx wordxyxy wordxyzxyzxyz 例如: string=“此SSSSSS是echooooooo stringggg.replaceAceACE repeatededededed groupsss of symbolsSS” 我找到了一种方法来替换一些重复的组合,如下所示: re.sub(r'([a-z]{1,3})\1+',r'\1',string) 我得到了这些结果: 这是echoo

我有一个字符串,它由在末尾有重复字符的单词组成。 这些字符可以是这样的组合:

  • wordxxxx
  • wordxyxy
  • wordxyzxyzxyz
例如:

string=“此SSSSSS是echooooooo stringggg.replaceAceACE repeatededededed groupsss of symbolsSS”

我找到了一种方法来替换一些重复的组合,如下所示:

re.sub(r'([a-z]{1,3})\1+',r'\1',string)

我得到了这些结果:

这是echoooo stringg。替换重复的符号组


如何更改正则表达式以删除所有重复的字符及其组合?

您的正则表达式几乎是正确的

  • 您需要将
    添加到捕获组中,使其尽可能少地匹配(“惰性匹配”,而不是尽可能多地匹配的默认“贪婪”行为)

  • 我还使用了
    +
    而不是
    {1,3}
    ,因为将重复限制在
    3
    似乎是任意的

  • 您可以观察两种行为之间的差异:vs。 请注意:

  • 贪婪行为将
    aaaa
    视为
    aa*2
    而不是
    a*4

  • 贪婪的行为只适用于长时间的重复<代码>AAAA被视为

    aa*2+a
    因此,替换结果将是
    aaa
    ,而不是
    a


输出

This
is
echo
string.
Replace
repeated
groups
of
symbols
一行解决方案

string = "Thisssssssss isisisis echooooooo stringggg. Replaceaceaceace repeatedededed groupssss of symbolssss"
print(re.sub(r'([a-z]+?)\1+', r'\1', string))
#This is echo string. Replace repeated groups of symbols

这里可能值得一提的是,在使用贪婪量词时到底出了什么问题,即“ssss”被分析为“ss”*2,而不是“s”*4。@alaniwi谢谢,我补充了这个解释+一个关于奇怪长度重复的有趣见解。
string = "Thisssssssss isisisis echooooooo stringggg. Replaceaceaceace repeatedededed groupssss of symbolssss"
print(re.sub(r'([a-z]+?)\1+', r'\1', string))
#This is echo string. Replace repeated groups of symbols