Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the regex to replace a single space between a closing brace and a letter?

I want to replace all occurrences of

  • case 1: a single space between 2 letters
  • case 2: a single space between a closing brace } and a letter

with \times such that

'a^{3} + 3 a^{2} b + 3 a b^{2} + b^{3}'

becomes

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

'a^{3} + 3 \\times a^{2} \\times b + 3 \\times a \\times b^{2} + b^{3}'

I can successfully do the first case with \b\s\b but I don’t know how to do for the second one.

My attempt below just produces

'a^{3} + 3 \\times a^{2}  b + 3 \\times a \\times b^{2} + b^{3}'

where I fail to put \\times between a^{2} and b.

import re
import sympy
from IPython.display import display
a,b = sympy.symbols('a b')

f = (a+b)**3
expr = sympy.latex(f.expand())
display(expr)
expr = re.sub(r'(\b\s\b)|(IDONTKNOW)', r' \\times ', expr)
display(expr) 

>Solution :

Like this?

re.sub(r'(?<=[}\w])\s(?=\w)', r' \times ', expr)

The lookarounds are assertions which do not include the text in the match. (?<=...) requires the text before the main match to be either } or an alphanumeric, and (?=...) requires the text after the main match to be an alphanumeric.

(\w is not exactly "an alphanumeric"; it matches numbers and underscores in addition to alpbabetics. Probably replace it with e.g. [A-Za-z] if you strictly need to match only English alphabetics.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading