[英]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.