user2965473 user2965473 - 1 year ago 100
Python Question

python re.sub - alternative replacement patterns

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?

PS. code specifics here are irrelevant, it's a general question.

Answer Source

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
...        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