I'm trying to "parse" some LaTeX code. LaTeX uses some special characters such as %, #, {, } and delimits inline math environments with $ … $.
What I need is to escape (\) all special chars that are not already escaped and are not inside $ … $.
For example, for the provided entry
#s{o}me\%thing $ \text{a} $
I need to return:
\#s\{o\}me\%thing $ \text{a} $
Note that the already escaped \%, as well as the \text{a} within $ … $, remain untouched.
I'm using Python's re.sub to do that, and this way I can ignore the escaped ones, but I don't know how to ignore $ … $ environments. My current code is:
string = "#s{o}me\%thing $ \text{a} $"
re.sub(r'([^\\]?)((?:%|#|{|}|&))', r"\1\\\2", string)
# Expected output: "\#s\{o\}me\%thing $ \text{a} $"
# Actual output: "\#s\{o\}me\%thing $ \text\{a\} $"
At this time, my code returns, for the example above, the following:
\#s\{o\}me\%thing $ \text\{a\} $
Any suggestions??