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>I was able to simplify this a little bit by using a negated set:</p>

<pre><code>import re
s = 'H&gt;=ll&lt;=o=wo+rl-d.my name!'
op = 'H &gt;= ll &lt;= o = wo + rl - d.my name!'
s = re.sub(r'([^a-zA-Z0-9.])+',' \\1 ',r'H&gt;=ll&lt;=o=wo+rl-d.myname!')
print (s)
</code></pre>

<p>Other commenters above mentioned the reason this is happening is because the - wasn't working as you intended it to. </p>

python regex