python re.sub - alternative replacement patterns

六眼飞鱼酱① 提交于 2019-11-27 08:20:28

问题


I want to provide alternative replacement patterns to 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.


回答1:


You can pass a function to 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. If [A-Z]+ was matched, x is the replacement string else [a-z]+ was matched and y is the replacement string.

For more information : doc




回答2:


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.



来源:https://stackoverflow.com/questions/37776934/python-re-sub-alternative-replacement-patterns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!