Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex replace capture

Tags:

python

regex

I'm trying to add one space before and after +-, using re.sub (only) what expression to use?

import re

text = """a+b
a+b-c
a + b - c
a+b-c+d-e
a + b - c + d - e"""

text = re.sub('(\s?[+-]\s?)', r' \1 ', text)
print(text)

expected result:

a + b
a + b - c
a + b - c
a + b - c + d - e
a + b - c + d - e

<script type="text/javascript" src="//cdn.datacamp.com/dcl-react.js.gz"></script>

<div data-datacamp-exercise data-lang="python">
  <code data-type="sample-code">
    import re

    text = """a+b
      a+b-c
      a + b - c
      a+b-c+d-e
      a + b - c + d - e
      """

    text = re.sub('(\s?[+-]\s?)', r' \1 ', text)
    print(text)
  </code>
</div>
like image 968
ewwink Avatar asked Mar 06 '23 00:03

ewwink


1 Answers

Try capturing only the [+-], and then replace with that group surrounded by spaces:

text = re.sub('\s?([+-])\s?', r' \1 ', text)

<script type="text/javascript" src="//cdn.datacamp.com/dcl-react.js.gz"></script>

<div data-datacamp-exercise data-lang="python">
  <code data-type="sample-code">
import re

text = """a+b
a+b-c
a + b - c
a+b-c+d-e
a + b - c + d - e
"""

text = re.sub('\s?([+-])\s?', r' \1 ', text)
print(text)
  </code>
</div>

You also might consider repeating the \ss with * instead of ?, so that, for example, 3 + 5 gets prettified to 3 + 5:

\s*([+-])\s*
like image 104
CertainPerformance Avatar answered Mar 15 '23 04:03

CertainPerformance