python 正则表达式使用函数替换

使用替换函数,能够实现对匹配的不同内容实现不同的替换方式

def dashrepl(matchobj):
    if matchobj.group(0) == '-': return ' '
    else: return '-'
 
 
re.sub('-{1,2}', dashrepl, 'pro----gram-files')
 
#结果为 'pro--gram files'
python-basic/regexp-function.txt · 最后更改: 2010/06/02 09:18 (外部编辑)
2007~2011 Copyright @ http://www.pythonclub.org