正則替換可以使用函數
例如:替換字符串中所有#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