python - Manipulating substrings found to replace -
this question has answer here:
- python regex replace ascii value 2 answers
i want replacement depend on found. ie. example of i'm after might following
def f(x): return str(int(x) + 1) print(re.sub(r"(\d)", f(r"\1"), "123")) #print 234
however, doesn't work of course. way of doing intend without having keep track of position/length of found string , replacing on next line? ie. i'm looking way in 1 go.
note actual example i'm working on isn't simple. i'm making function interprets mathematical calculation string input.
eg. "2 + 4 * 6 / 3"
the idea function replace "4 * 6" 24, "24 / 3" 8, , "2 + 8" 10. search appropriate pairs , follow bidmas using regex.
maybe it's simplistic, build simple evaluator applying regexes first on multiply, on add operators, using replacement function:
import re s = "4 + 6 * 7" def replfunc(m): = int(m.group(1)) b = int(m.group(3)) op = m.group(2) if op=="*": return str(a*b) elif op=="+": return str(a+b) op in "*+": s = re.sub("(\d+)\s*({})\s*(\d+)".format(re.escape(op)),replfunc,s)
here, regex tries match "number operator number" (with optional spaces in between) , calls replacement function on match.
the replacement function acts accordignly, converting integer, peforming relevant operation, , returning string replaced.
of course, isn't designed process parenthesized expressions , never be, consider third-party evaluators instead, simpleeval (searching in pypi gives dozens of results)
Comments
Post a Comment