I know that you are after regex, but you can use a simple loop to achieve the same:
def max_repeats(s, max=2): last = '' out = [] for word in s.split(): same = 0 if word != last else same + 1 if same < max: out.append(word) last = word return ' '.join(out)
As a bonus, I allowed to specify a different maximum number of repetitions (default 2). If there is more than one space between each word, it will be lost. It is up to you whether you think this is a bug or function :)
source share