正则表达式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": "185xxxx64", "pwd": "123456"}
replace(s, d) #替换后的s: {"mobilephone": "185xxxx864", "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': '185xxxx64', 'borrow_pwd': '123456'}
s=replace(s, d)
print(s)


posted @ 2020-04-06 17:18  测试媛S  阅读(168)  评论(0)    收藏  举报