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 true
a = re.compile('(?P.*)')
# return _'yes'_ or 'no' based on
a.sub('(?(\g)yes|no)', 'word')
'(?(word)yes|no)'
I expected either a 'yes' or 'no,' not the actual test.
What I get from this is that is seen but the regex conditional isn't being executed. Is there another way of accomplishing this?
I tried with re.sub(pat, rep, str) with same results.
解决方案
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
def replTxt(match):
return 'yes' if match.group('test') else 'no'
a = re.compile('(?P.+)')
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[a-z]+)?\d.