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

2024-06-28 20:45:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

  • 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。替换重复的符号组

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


Tags: of字符串string字符单词末尾sssssswordxyxy
2条回答

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

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

  • 我还使用了+而不是{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

一行解决方案

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

相关问题 更多 >