0
点赞
收藏
分享

微信扫一扫

【猫狗日记】 python正则表达式 ——基础

余寿 2022-03-23 阅读 70
python
"""
不规律的数据 使用正则表达式
正则表达式 : 匹配指定规则的字符串

使用:
"""
"""

import  re
test_str = "py1235thonp0@#$%sss#@|S|\s"
# res = re.findall("py",test_str)
# res = re.findall("[phe]",test_str)
# res = re.findall("p.",test_str)
# res = re.findall("\d",test_str) #匹配数字
# res = re.findall("\D",test_str)  #匹配非数字
# res = re.findall("\s",test_str) # 取空格
# res = re.findall("\S",test_str) #去空格
# res2 = "".join(res)
# res = re.findall("\W",test_str)  #匹配特殊字符
res = re.findall("\w",test_str) #匹配非特殊字符
    
print(res)
# print(res2)
"""
"""
# 多字符匹配
import  re

test_str = "py1235ppppy pyyyypp"
# res = re.findall("p*",test_str) # 匹配p  没有则返回空,最后会默认匹配一次为空
res1 = re.findall("py+",test_str) #贪婪模式  匹配+ 前一个字符出现1次或者无数次
res2 = re.findall("py?",test_str) #非贪婪模式    ?匹配前一个字符出现0次或者1次
res3 = re.findall("py{2}",test_str)
res4 = re.findall("py{1,2}",test_str)
print(res1,res2)
print(res3)
"""
import re

# tets_str = "hello python"
# res = re.findall("he|ll",tets_str)
# res2 = re.findall("^he",tets_str)
# res3 = re.findall("n$",tets_str)
# print(res)
# print(res2)
# print(res3)
# 分组匹配  用于取出接口返回对应key的value
jsondate = {"key1": "value1", "key2": "value2"}
test_demo = '{"#key1#":"value","#key2#":"value2"}'
res = re.findall("#(\w.+?)#", test_demo)
print(type(res))
for key in res:
    print(jsondate[key])
举报

相关推荐

0 条评论