这里会显示出您选择的修订版和当前版本之间的差别。
python-basic:regexp-function [2010/06/02 01:18] |
python-basic:regexp-function [2010/06/02 01:18] (当前版本) |
||
---|---|---|---|
行 1: | 行 1: | ||
+ | ====== python 正则表达式使用函数替换 ====== | ||
+ | |||
+ | 使用替换函数,能够实现对匹配的不同内容实现不同的替换方式 | ||
+ | |||
+ | <code python> | ||
+ | def dashrepl(matchobj): | ||
+ | if matchobj.group(0) == '-': return ' ' | ||
+ | else: return '-' | ||
+ | |||
+ | |||
+ | re.sub('-{1,2}', dashrepl, 'pro----gram-files') | ||
+ | |||
+ | #结果为 'pro--gram files' | ||
+ | </code> | ||
+ | |||
+ | |||
+ | |||
+ | |||