【问题标题】:Regex to remove duplicated characters and combinations正则表达式删除重复的字符和组合
【发布时间】:2020-12-05 00:52:52
【问题描述】:

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

  • wordxxxx
  • wordxyxyxy
  • wordxyzxyzxyz

例如:

string = "Thisssssssss isissis echooooooo stringggg. Replaceaceaceace 重复的符号组ssssss"

我找到了一种方法来替换一些重复的组合,这样:

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

我得到了这些结果:

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

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

【问题讨论】:

    标签: python regex string duplicates


    【解决方案1】:

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

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

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

    • 您可以观察到这两种行为之间的区别:greedylazy。 请注意:

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

      2. 贪婪行为仅适用于偶数长度的重复。 aaaaa 被视为

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


    for word in "Thisssssssss isisisis echooooooo stringggg. Replaceaceaceace repeatedededed groupssss of symbolssss".split():
        print(re.sub(r'([a-z]+?)\1+', r'\1', word))
    

    输出

    This
    is
    echo
    string.
    Replace
    repeated
    groups
    of
    symbols
    

    【讨论】:

    • @alaniwi 谢谢,我添加了这个解释 + 关于奇数重复的有趣见解。
    【解决方案2】:

    一个班轮解决方案

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-02
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 2018-01-26
      • 2021-10-13
      • 1970-01-01
      相关资源
      最近更新 更多