For doing a regex substitution, there are three things that you give it:
I looked at the documentation and it seems like you can pass a function reference into the re.sub
:
import re
def re_sub_verbose(pattern, replace, string):
def substitute(match):
print 'Matched:', match.group(0)
print 'Replacing with:', match.expand(replace)
return match.expand(replace)
result = re.sub(pattern, substitute, string)
print 'Final string:', result
return result
And I get this output when running re_sub_verbose("(orig.*?l)", "not the \\1", "This is the original string.")
:
Matched: original
Replacing with: not the original
This is the not the original string.