我想正則表達式(在Python),鑑於類似的句子:如何使用Python中的正則表達式刪除單詞中的多個後續字符?
heyy how are youuuuu, it's so cool here, cooool.
其轉換爲:
heyy how are youu, it's so cool here, cool.
,這意味着最大的1次的字符可以重複,如果它更比它應該被刪除。
heyy ==> heyy
youuuu ==> youu
cooool ==> cool
我想正則表達式(在Python),鑑於類似的句子:如何使用Python中的正則表達式刪除單詞中的多個後續字符?
heyy how are youuuuu, it's so cool here, cooool.
其轉換爲:
heyy how are youu, it's so cool here, cool.
,這意味着最大的1次的字符可以重複,如果它更比它應該被刪除。
heyy ==> heyy
youuuu ==> youu
cooool ==> cool
您可以在模式中使用反向引用匹配重複的字符,然後與匹配字符的兩個實例代替它,在這裏(.)\1+
將匹配包含相同字符兩次或更多次的模式,代之以只有兩種情況下,通過\1\1
:
import re
re.sub(r"(.)\1+", r"\1\1", s)
# "heyy how are youu, it's so cool here, cool."
創建一個新的文本,只如果沒有連續3次
text = "heyy how are youuuuu, it's so cool here, cooool."
new_text = ''
for i in range(len(text)):
try:
if text[i]==text[i+1]==text[i+2]:
pass
else:
new_text+=text[i]
except:
new_text+=text[i]
print new_text
>>>heyy how are youu, it's so cool here, cool.
添加到它
eta:嗯只是注意到你要求「正則表達式」,所以批准答案更好;雖然這個作品
很好用!謝謝。 – Ash