码迷,mamicode.com
首页 > 其他好文 > 详细

正则表达式 re

时间:2020-04-06 17:25:37      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:pre   count   pwd   use   imp   dal   span   print   正则   

# 正则  正则式针对字符串的操作
import re

s = ‘{"mobilephone": "${borrow_user}", "pwd": "${borrow_pwd}"}‘
d = {"mobilephone": "18511295864", "pwd": "123456"}
p = ‘\$\{(.*?)}‘

# 查找一个
m = re.search(p, s)
print(m) # <re.Match object; span=(17, 31), match=‘${borrow_user}‘>
g = m[1]
print(g) # borrow_user

#查找所有
m_all = re.findall(p, s)
print(m_all) # 返回列表 [‘borrow_user‘, ‘borrow_pwd‘]

# 查找并替换全部, 【count=1,就替换一次】
rep = ‘18511295864‘
m = re.sub(p, rep, s, count=1)
print(m) # {"mobilephone": "18511295864", "pwd": "${borrow_pwd}"}


正则表达式 re

标签:pre   count   pwd   use   imp   dal   span   print   正则   

原文地址:https://www.cnblogs.com/sophia-985935365/p/12642709.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!