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.
s = 'H>=ll<=o=wo+rl-d.my name!'
op = 'H >= ll <= o = wo + rl - d.my name!'
re.sub(r'((<=)|(>=)|[+-=*/])+',' \\1 ',r'H>=ll<=o=wo+rl-d.myname!')
'H >= ll <= o = wo + rl - d . my name!'
The reason for the spaces around the dot is
-. Concrete it is
[+-=], which is a character class with characters from
=, which includes
To avoid this, you must escape
re.sub(r'((<=)|(>=)|[+\-=*/])+',' \\1 ',r'H>=ll<=o=wo+rl-d.myname!')
As @LaurentLAPORTE mentioned, you can also put
- at the beginning or the end of a character class, e.g.
[+=*/-] will both do the trick.