今天逛百度知道,無意發現,原來re.sub中的替換項可以是一個函數。
這個函數接受一個參數。然后根據需求,返回應該替換的字符串。
IDLE 2.6.5
>>> import re
>>> r=re.compile(r'a{1,2}')
>>> def myrepl(m):
s=m.group(0)
if s=='a':
return 'one a'
else:
return 'two a'
>>> r.sub(myrepl,'a aa aaa')
'one a two a two aone a'
>>>
下面是摘自python文檔(The Python Standard Library 8.2. re — Regular expression operations):
Ifrepl is a function, it is called for every non-overlapping occurrence ofpattern. The function takes a single match object argument, and returns the replacement string. For example:
>>> defdashrepl(matchobj):
... ifmatchobj.group(0)=='-':return' '
... else:return'-'
>>> re.sub('-{1,2}',dashrepl,'pro----gram-files')
'pro--gram files'
閱讀全文 類別:Python 查看評論文章來源:
http://hi.baidu.com/mirguest/blog/item/42411d14ae7fcf0b972b43fc.html