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>So when you do a character class like:</p>

<pre><code>[+-=]
</code></pre>

<p>The regex reads that as any character between <code>+</code> (ASCII 43) and <code>=</code> (ASCII 61). It's similar to:</p>

<pre><code>[A-Z]
</code></pre>

<p>So you have to escape the <code>-</code>:</p>

<pre><code>r'((&lt;=)|(&gt;=)|[+\-=*/])+'
</code></pre>

<p>(Or put the <code>-</code> at the end as suggested in the comments: <code>[+=-]</code>)</p>

<p><a href="https://regex101.com/" rel="nofollow">Regex101</a> is very handy for analyzing regex patterns like this. You can see the problem with your pattern <a href="https://regex101.com/r/zDZAKf/1" rel="nofollow">here</a></p>

python regex