2017-03-08 3 views
2

私はその与えられたような文(Pythonで)正規表現たい:文字を繰り返すことができ、それはより多くのだ場合は1時間の最大値を意味Pythonで正規表現を使用して単語内の複数の結果文字を削除するにはどうすればよいですか?

heyy how are youu, it's so cool here, cool. 

heyy how are youuuuu, it's so cool here, cooool. 

はに変換しますそれよりも削除する必要があります。あなたが(.)\1+ここでは、繰り返し文字にマッチするパターン内の参照をバックに使用して、一致した文字の2つのインスタンスに置き換えることができ

heyy ==> heyy 
youuuu ==> youu 
cooool ==> cool 

答えて

1

はと交換し、同じ文字を2回以上含まれているパターンと一致します\1\1によってのみ2つのインスタンス:

import re 
re.sub(r"(.)\1+", r"\1\1", s) 
# "heyy how are youu, it's so cool here, cool." 
+1

が素晴らしいです!ありがとう。 – Ash

0

は、新しい空のテキストを作成し、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. 
がない場合にのみ、それに追加します

ええええええええええええええええええええええええええええええええええええええええええええええええ、これは動作しますが

関連する問題