今天逛百度知道,无意发现,原来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