5
>>> base64_encode = lambda url : url.encode('base64').replace('\n', '')
>>> s = '<A HREF="http://www.google.com" ID="test">blah</A>'
>>> re.sub(r'(?<=href=")([\w:/.]+)(?=")', base64_encode(r'\1'), s, flags=re.I)
<A HREF="XDE=" ID="test">blah</A>

http://www.google.com字符串的base64编码aHR0cDovL3d3dy5nb29nbGUuY29t不是XDE=,是的编码\1

如何将捕获的组传递给函数?

4

2 回答 2

11

您将一个函数传递给re.sub然后从那里拉出该组:

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

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

re.sub(...,base64_encode,s,flags=re.I)
于 2013-06-16T18:00:00.557 回答
4

编写您的函数以获取单个参数,该参数将是一个匹配对象(有关这些的详细信息,请参见http://docs.python.org/2.7/library/re.html#match-objects)。在您的函数内部,用于m.group(1)从匹配对象中获取第一组m

当你将函数传递给 re.sub 时,不要使用括号:

re.sub("some regex", my_match_function, s, flags=re.I)
于 2013-06-16T18:00:37.543 回答