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>One simple way is that instead of <code>+</code> you can split the regex into two as</p>

<pre><code>&gt;&gt;&gt; re.sub(r'(?:{{TAG}}\s*)*{{TAG}}', r'{{TAG}}', string)
'{{TAG}} some other text. {{TAG}}'
</code></pre>

<ul>
<li><p><code>(?:{{TAG}}\s*)*</code> Matches zero or more <code>{{TAG}}</code> with space at the end.</p></li>
<li><p><code>{{TAG}}</code> Match the last <code>{{TAG}}</code> without any space.</p></li>
</ul>

<hr>

<p>You can also solve this using a positive look ahead </p>

<pre><code>&gt;&gt;&gt; re.sub(r'{{TAG}}\s*(?={{TAG}})', r'', string)
'{{TAG}} some other text. {{TAG}}'
</code></pre>

<ul>
<li><p><code>{{TAG}}\s*</code> Matches one <code>{{TAG}}</code> followed by space.</p></li>
<li><p><code>(?={{TAG}}</code> Positive look ahead. Checks if the <code>{{TAG}}</code> matched in the above point is followed by another <code>{{TAG}}</code></p></li>
</ul>

python regex