簡體   English   中英

在re.sub()中調用捕獲的組上的函數

[英]Calling a function on captured group in re.sub()

>>> 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的編碼。

如何將捕獲的組傳遞給函數?

您將函數傳遞給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)

編寫函數以獲取單個參數,該參數將是匹配對象(有關這些參數的詳細信息,請參閱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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM