regex - merge repeated consecutive words preserving last space
<p>I have a string like this</p>

<p><code>{{TAG}} {{TAG}}{{TAG}} {{TAG}} some other text. {{TAG}} {{TAG}}</code></p>

<p>and I am trying to merge multiple consecutive occurrences of <code>{{TAG}}</code> into one. So I have this regex <code>re.sub(r'(({{TAG}})\s*)+', "{{TAG}}", text)</code> which works fine to remove multiple occurrences and gives me this </p>

<p><code>{{TAG}}some other text. {{TAG}}</code>.</p>

<p>But its taking one extra space at the end, which I am trying to avoid. So that I get </p>

<p><code>{{TAG}} some other text. {{TAG}}</code></p>

<p>Found a similar question <a href="http://stackoverflow.com/questions/14930320/regular-expression-matching-a-sequence-of-consecutive-words-with-spaces-except-f">here</a>, but that didn't solve my problem. Any suggestions to improve my regex or any other alternative in python?</p>

<p>You're matching <code>{{TAG}}\s*</code> once or more, but you want to match <code>{{TAG}}</code> once, followed by zero or more instances of <code>\s*{{TAG}}</code>.</p>

<pre><code>re.sub('({{TAG}}(?:\s*{{TAG}})*)', '{{TAG}}', text)
</code></pre>

python regex