mareoraft mareoraft - 1 year ago 93
Perl Question

if statement in python regex substitution

I have a regex that searches for

. If it finds
, it replaces it with
. If it finds
, it replaces it with

Here is what it looks like in Perl:

m =~ s/(this)|(that)/ "ONE" !!x $1 . "TWO" !!x $2 /eg

is the eval option.
is a concatenation.
acts as an if statement.

How can I do the same thing in Python 3? I'm looking for something like:

m = re.sub(r"(this)|(that)", ("ONE" * bool( + ("TWO" * bool(, m, flags=re.EVAL)

I guess I have two main roadblocks. Firstly, I don't know how to obtain the
object within a regex substitution. Secondly, I don't know if eval is supported by python or what the best alternative is.

Answer Source

Python has no strange language syntax related to regular expressions - they are performed in well behaved function calls.

So instead of a part of the call arguments that are executed on match, what you have is a callback function: all you have to do is to put a callable object as the second argument, instead of the substitution string. The callable receives the match object as its sole argument. In this case, all you need is an inline if - so you can even define the callable as a lambda expression:

t = "this this that"
m = re.sub(r"(this)|(that)", lambda x: "ONE" if == "this" else "TWO", t   )