在Python中搜索和替换

sub是使用正则表达式的最重要的re方法之一。

语法

re.sub(pattern, repl, string, max=0)

此方法用repl替换字符串中所有出现的RE模式,除非提供了max,否则将替换所有出现的RE模式。此方法返回修改后的字符串。

示例

#!/usr/bin/python
import re
phone = "2004-959-559 # This is Phone Number"
# Delete Python-style comments
num = re.sub(r'#.*$', "", phone)
print "Phone Num : ", num
# Remove anything other than digits
num = re.sub(r'\D', "", phone)
print "Phone Num : ", num

输出结果

执行以上代码后,将产生以下结果-

Phone Num : 2004-959-559
Phone Num : 2004959559