A
A
Alexey Poloz2018-02-23 12:54:59
Python
Alexey Poloz, 2018-02-23 12:54:59

Regular expressions How to remove all repeated letters more than 2 times in a row?

Remove all repetitions in a row beyond 2 characters for letters of any language
For example:

'veююююvno b fffa a aaaaa nkacvak 777 aa' -> 'veююvno b ffa a aa nkacvak 777 aa'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2018-02-23
@kosyachniy

Heh, even screwed up in the example)

print(re.sub(r'(\w)\1+', r'\1\1',
             'veююююvno b fffa a aaaaa nkacvak 777 aa'))

Or does it not apply to numbers? Then it's more difficult:
def f(m):
    s = m.group(0)
    return s if s[0].isdigit() else s[:2]

print(re.sub(r'(\w)\1+', f,
             'на любом языке - так на любом 777 aa მუუუუნჯი 慕尼尼尼尼黑 '))

ps found a better solution:
print(re.sub(r'([^\W\d])\1+', r'\1\1',
             'veююююvno b fffa a aaaaa nkacvak 777 aa მუუუუნჯი 慕尼尼尼尼黑 '))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question