Skip to content Skip to sidebar Skip to footer

Using If-then-else Conditionals With Python Regex Replacement

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}'

Solution 1:

You may pass the match to a method where you may check if a certain group matched or not, and then build the replacement dynamically applying your conditions using standard Python means:

import re
defrepl(x):
    returnr"\frac{{{0}}}{{{1} - {2}}}".format(x.group("numer"),
        (x.group("denom1") if x.group("neg") else x.group("denom2")),
        (x.group("denom2") if x.group("neg") else x.group("denom1")))

string1 = r"- \frac{2}{- 4 \sqrt{2} + 2}"
string2 = r"\frac{2}{- 4 \sqrt{2} + 2}"
pattern = r"(?P<neg>- )?\\frac{(?P<numer>\d*)}{- (?P<denom1>\d* ?\\sqrt{\d*}) \+ (?P<denom2>\d*)\}"print(re.sub(pattern, repl, string1)) # => \frac{2}{4 \sqrt{2} - 2}print(re.sub(pattern, repl, string2)) # => \frac{2}{2 - 4 \sqrt{2}}

See Python demo

Post a Comment for "Using If-then-else Conditionals With Python Regex Replacement"