I am trying to use a the re.sub() method. I have a string which I backreference with '\\1'. In my substitution parameter, is there anyway I can pass \\1 through a function?


For example

output = re.sub(r'blah blah blah(\d+)','\\SOME_FUNCTION(\\1)',string)

where any instance of (\d+) will replaced by the output when passed through the function SOME_FUNCTION()

You must use a helper function which takes a match object as argument

def sub_helper(match):
    return SOME_FUNCTION(match.group(1))

output = re.sub(r'blah blah blah(\d+)', sub_helper, string)