简体   繁体   中英

if statement in python regex substitution

I have a regex that searches for this or that . If it finds this , it replaces it with ONE . If it finds that , it replaces it with TWO .

Here is what it looks like in Perl:

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

e is the eval option. . is a concatenation. x!! 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(match.group(1))) + ("TWO" * bool(match.group(2))), m, flags=re.EVAL)

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

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 x.group() == "this" else "TWO", t   )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM