I would like to use re.sub to turn this:
string = '\\(2 \\, e^{\\left(2 \\, x\\right)} \\sin\\left(2 \\, x\\right) + 2 \\, e^{\\left(2 \\, x\\right)} \\cos\\left(2 \\, x\\right)\\)'
into this:
'\\(2 \\, e^{2 \\, x} \\sin\\left(2 \\, x\\right) + 2 \\, e^{2 \\, x} \\cos\\left(2 \\, x\\right)\\)'
This is my best attempt, but it does not work:
re.sub(r'(?P<left-edge>e\^{\\left\()(?P<input>.*)(?P<right-edge>\\right\)})','e^{\g<input>}',string)
Note that <input> needs to handle an arbitrary expression, while <left-edge> and <right-edge> are fixed character strings.
I am assuming it has to do with the special characters involved, but several dozen attempts demonstrate that it is beyond my expertise.
Backslashes in regular expressions must be escaped. You used
r''so they do not have to be escaped as characters in Python string, but that’s not enough for them to be interpreted as literal\chars in regexes. Use double backslashes:Were it not for
r'', they would have to be escaped twice, i.e. quadrupled, in order to satisfy both Python interpreter and regexp engine:(Additionally, you also forgot to escape one of
^carets. I corrected that in both of my examples.)