I am trying to replace whitespaces, in latex that is contained in a markdown document, with \\; using regex.
In the md package I'm using, all latex is wrapped in either $ or $$
I would like to change the following from
"dont edit this $result= \frac{1}{4}$ dont edit this $$some result=123$$"
to this
"dont edit this $result=\\;\frac{1}{4}$ dont edit this $$some\\;result=123$$"
I have managed to do it using the messy function below but would like to use regex for a cleaner approach. Any help would be appreciated
import re
vals = r"dont edit this $result= \frac{1}{4}$ dont edit this $$some result=123$$"
def cleanlatex(vals):
vals = vals.replace(" ", " ")
char1 = r"\$\$"
char2 = r"\$"
indices = [i.start() for i in re.finditer(char1, vals)]
indices += [i.start() for i in re.finditer(char2, vals.replace("$$","~~"))]
indices.sort()
print(indices)
# check that no of $ or $$ are even
if len(indices) % 2 == 0:
while indices:
start = indices.pop(0)
finish = indices.pop(0)
vals = vals[:start] + vals[start:finish].replace(' ', '\;') + vals[finish:]
vals = vals.replace(" ", " ")
return vals
print(cleanlatex(vals))
Output:
[18, 39, 60, 78]
dont edit this $result=\\;\frac{1}{4}$ dont edit this $$some\\;result=123$$