Python Regex handling dot character
<p>While using regex in python I came across a scenario.
What I am trying to do is if a string has operators, I want to add space before and after the operator.</p>

<pre><code>s = 'H&gt;=ll&lt;=o=wo+rl-d.my name!'
op = 'H &gt;= ll &lt;= o = wo + rl - d.my name!'
</code></pre>

<p>seemed pretty straight forward, so I came up with the following expression:</p>

<pre><code>re.sub(r'((&lt;=)|(&gt;=)|[+-=*/])+',' \\1 ',r'H&gt;=ll&lt;=o=wo+rl-d.myname!')
</code></pre>

<p>but the result I am getting using this is :</p>

<pre><code>'H &gt;= ll &lt;= o = wo + rl - d . my name!'
</code></pre>

<p>Its adding a space after every dot (.) encountered, even though I haven't mentioned it in my regex.</p>

<p>I am using python 2.7 and would really appreciate if you can shed some light on this.</p>

<p>The reason for the spaces around the dot is <code>-</code>. Concrete it is <code>[+-=]</code>, which is a character class with characters from <code>+</code> until <code>=</code>, which includes <code>.</code>.</p>

<p>To avoid this, you must escape <code>-</code> with <code>\-</code>, e.g. </p>

<pre><code>re.sub(r'((&lt;=)|(&gt;=)|[+\-=*/])+',' \\1 ',r'H&gt;=ll&lt;=o=wo+rl-d.myname!')
</code></pre>

<hr>

<p>As @LaurentLAPORTE mentioned, you can also put <code>-</code> at the beginning or the end of a character class, e.g. <code>[-+=*/]</code> or <code>[+=*/-]</code> will both do the trick.</p>

python regex