Python中的re模块提供了re.sub用户替换字符串中的匹配项。
语法:
re.sub(pattern,repl,string,count=0)
参数:
- pattern : 正则中的模式字符串。
- repl : 替换的字符串,也可为一个函数。
- string : 要被查找替换的原始字符串。
- count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。
phone = "2004-959-559 # 这是一个电话号码"
# 删除注释
num = re.sub(r'#.*$', "", phone)
print ("电话号码 : ", num)
# 移除非数字的内容
num = re.sub(r'\D', "", phone)
print ("电话号码 : ", num)
repl除了可以使用一个字符串用来表示替换后的结果以外,还可以传入一个函数。
def double(matched):
test = int(matched.group('test'))
return str(test * 2)
print(re.sub(r'(?P<test>\d+)', double, 'hello23hi34')) # hello46hi68