[英]python re.sub - alternative replacement patterns
I want to provide alternative replacement patterns to re.sub.我想为 re.sub 提供替代替换模式。
Let's say i've got two search patterns as alternatives, like this:假设我有两种搜索模式作为替代,如下所示:
re.sub(r"[A-Z]+|[a-z]+", replacementpattern, string)
and instead of providing one replacement pattern I would like to somehow catch which search pattern alternative was matched and provide alternative replacement patterns.而不是提供一种替换模式,我想以某种方式捕获匹配的搜索模式替代并提供替代替换模式。 Is this possible?
这可能吗? Thanks.
谢谢。
PS.附注。 code specifics here are irrelevant, it's a general question.
这里的代码细节无关紧要,这是一个普遍的问题。
You can pass a function to re.sub()
.您可以将函数传递给
re.sub()
。 In the function you can return the value needed based on the captured group.在函数中,您可以根据捕获的组返回所需的值。 A simple code for illustration:
一个简单的代码说明:
>>> def fun(m):
... if m:
... if m.group(1):
... return 'x'
... else:
... return 'y'
>>>print re.sub(r"([A-Z]+)|([a-z]+)", fun , "ab")
The function fun()
checks if the match succeeded and based on the captured group, returns the replacement string.函数
fun()
检查匹配是否成功,并根据捕获的组返回替换字符串。 If [AZ]+
was matched, x
is the replacement string else [az]+
was matched and y
is the replacement string.如果
[AZ]+
匹配, x
是替换字符串,否则[az]+
匹配, y
是替换字符串。
Usually, you would just use two replacements:通常,您只需使用两个替换:
re.sub(r"[A-Z]+", replacement1, string)
re.sub(r"[a-z]+", replacement2, string)
Anticlimactic, right?虎头蛇尾,对吧?
It's actually less code than the alternatives usually, and it's far clearer what you're doing.它实际上比通常的替代品更少的代码,而且你在做什么也更清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.