I am trying to use re.sub() to manipulate latex math expressions, specifically, replace strings such as
string1 = "- \frac{2}{- 4 \sqrt{2} + 2}" # with "\frac{2}{4 \sqrt{2} - 2}"
string2 = "\frac{2}{- 4 \sqrt{2} + 2}" # with "\frac{2}{2 - 4 \sqrt{2}}"
Here is the python code that raised an error("unmatched group").
pattern = r"(?P<neg>- )?\\frac{(?P<numer>\d*)}{- (?P<denom1>\d* ?\\sqrt{\d*}) \+ (?P<denom2>\d*)\}"
replacement = r"\\frac{\g<numer>}{(?(\g<neg>)(\g<denom2> - \g<denom1>)|(\g<denom1> - \g<denom2>))}"
key = sub(pattern, replacement, string)
I am sure that the pattern matches correctly because I tried using the re.sub()
without the conditional in the replacement argument and the code worked fine. Of course, in this case, the code works either for string1 or string2 but not both.
pattern = r"(?P<neg>- )?\\frac{(?P<numer>\d*)}{- (?P<denom1>\d* ?\\sqrt{\d*}) \+ (?P<denom2>\d*)\}"
replacement = r"\\frac{\g<numer>}{\g<denom1> - \g<denom2>}"
key = sub(pattern, replacement, string)
so is it a syntax problem and if that's the case, what's the problem? or If-then-else conditionals are not allowed in the replacement argument?