在re.sub()中调用捕获的组上的函数

时间:2013-06-16 17:57:42

标签: python regex

>>> 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的编码。

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

2 个答案:

答案 0 :(得分:7)

您将函数传递给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)

答案 1 :(得分:3)

编写函数以获取单个参数,该参数将成为匹配对象(有关这些参数的详细信息,请参阅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)
相关问题