Skip to content Skip to sidebar Skip to footer

Python Regex Conditional In Re.sub - How?

Is it possible to use python's regex conditionals in re.sub()? I've tried a number of variations without luck. Here's what I have. import re # match anything: always t

Solution 1:

If you want to perform a conditional substitution, use a function as the replace parameter.

This function accepts a match parameter (what has been caught) and its result is the text to be substituted in place of the match.

To refer in the replace function to the capturing group named test, use group('test').

Example program:

import re

defreplTxt(match):
    return'yes'if match.group('test') else'no'

a = re.compile('(?P<test>.+)')  
result = a.sub(replTxt, 'word')
print(result)

But I have such a remark:

There is no chance that no will ever be substituted by this program. If the regex doesn't match, replTxt function will just not be called.

To have the possibility that test group matched nothing, but something has been matched:

  • this capturing group should be conditional (? after it),
  • in order not to match an empty text, the regex should contain something more to match, e.g. (?P<test>[a-z]+)?\d.

Post a Comment for "Python Regex Conditional In Re.sub - How?"