I want the replacement to depend on what is found. ie. an example of what I'm after might be the following
def f(x):
return str(int(x) + 1)
print(re.sub(r"(\d)", f(r"\1"), "123"))
#print 234
However, that doesn't actually work of course. Is some way of doing what I intend without having to keep track of the position/length of the found string and then replacing it on the next line? ie. I'm looking for a way to do this in one go.
Note the actual example I'm working on isn't as simple. I'm making a function which interprets a mathematical calculation string input.
Eg. "2 + 4 * 6 / 3"
The idea would be for the function to replace "4 * 6" with 24, then "24 / 3" with 8, and finally "2 + 8" with 10. It will search for the appropriate pairs and follow BIDMAS using regex.
Maybe it's simplistic, but you could build some simple evaluator by applying regexes first on multiply, then on add operators, using a replacement function:
import re
s = "4 + 6 * 7"
def replfunc(m):
a = 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)
for op in "*+":
s = re.sub("(\d+)\s*({})\s*(\d+)".format(re.escape(op)),replfunc,s)
here, regex tries to match "number operator number" (with optional spaces in between) and calls the replacement function on match.
The replacement function acts accordignly, converting to integer, peforming the relevant operation, and returning back a string to be replaced.
Of course, this isn't designed to process parenthesized expressions and will never be, consider third-party evaluators instead, like simpleeval (searching in pypi gives dozens of results)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With