正则表达式re 封装

import re
def replace(s, d):
p = '\$\{(.*?)}'
for v in d.values():
print('v:', v)
s = re.sub(p, v, s, count=1) # 函数以列表返回字典中的所有值
print('替换后的s:', s)

s = '{"mobilephone": "${borrow_user}", "pwd": "${borrow_pwd}"}'
d = {"mobilephone": "18511295864", "pwd": "123456"}
replace(s, d) #替换后的s: {"mobilephone": "18511295864", "pwd": "123456"}

-------------------------------------------------------------------
第二种方式:
def replace(s, d):
p = '\$\{(.*?)}'
while re.search(p, s) is not None:
m = re.search(p, s)
key = m.group(1)
value = d[key]
s = re.sub(p, value, s, count=1)
return s

s = '{"mobilephone": "${borrow_user}", "pwd": "${borrow_pwd}"}'
d = {'borrow_user': '18511295864', 'borrow_pwd': '123456'}
s=replace(s, d)
print(s)


猜你喜欢

转载自www.cnblogs.com/sophia-985935365/p/12642962.html