Skip to content Skip to sidebar Skip to footer

Calling A Function On Captured Group In Re.sub()

>>> base64_encode = lambda url : url.encode('base64').replace('\n', '') >>> s = 'blah' >>> re.s

Solution 1:

You pass a function to re.sub and then you pull the group from there:

defbase64_encode(match):
    """
    This function takes a re 'match object' and performs
    The appropriate substitutions
    """

    group = match.group(1)
    ... #Code to encode as base 64return result

re.sub(...,base64_encode,s,flags=re.I)

Solution 2:

Write your function to take a single parameter, which will be a match object (see http://docs.python.org/2.7/library/re.html#match-objects for details on these). Inside your function, use m.group(1) to get the first group from your match object m.

And when you pass the function to re.sub, don't use parentheses:

re.sub("some regex", my_match_function, s, flags=re.I)

Post a Comment for "Calling A Function On Captured Group In Re.sub()"