[英]Regex to remove duplicated characters and combinations
我有一个字符串,它由末尾有重复字符的单词组成。 这些字符可能是这样的组合:
例如:
string = “Thissssssss isisisis echooooooo stringggg。替换aceaceace重复的符号组ssssss”
我找到了一种方法来替换一些重复的组合,这样:
re.sub(r'([az]{1,3})\1+', r'\1', string)
我得到这些结果:
Thisss 是 echoooo stringg。 替换重复的符号组
我应该如何更改正则表达式以删除所有重复的字符及其组合?
您的正则表达式几乎是正确的。
你需要添加?
到捕获组,因此它尽可能少地匹配(“惰性匹配”而不是尽可能匹配的默认“贪婪”行为)。
我还使用+
而不是{1,3}
因为将重复限制为3
似乎是任意的。
贪婪行为将aaaa
视为aa * 2
而不是a * 4
贪婪行为仅适用于偶数长度的重复。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.