正则替换可以使用函数
例如:替换字符串中所有#1.2.3.4#格式中的数字为0
import re
def replace(x):
def _replace(matched):
m = matched.group()
change = re.sub("d", '0', m)
return change
pattern = "#((d*.)+d+)#"
r = re.sub(pattern, _replace, x)
return r
x = "ab.c.d.#1.0.3.4# 2.2.2asdf"
r = replace(x)
print x
print r
输出:
ab.c.d.#1.0.3.4# 2.2.2asdf
ab.c.d.#0.0.0.0# 2.2.2asdf