正则表达式详解

一、re模块
1、作用:根据规则去匹配字符串
2、表达式:匹配字符串的规则
3、常用方法
findall():匹配所有的字符串,把匹配结果作为一个列表返回 (掌握)
match():匹配字符串的开始位置,如果开始位置没有就返回None
search():
在字符串中搜索,返回搜索到的第一个
finditer():匹配所有字符串,返回迭代器

二、正则匹配的分类
1、匹配单个字符:每次只匹配一个字符
元字符
.:  匹配任意字符,除\n以外

[]:匹配中括号中任意一个字符
/d

#1.: 匹配任意字符,除\n以外
res="h."
s="hello python"
result=re.findall(res,s)
print(result)

#2[]:匹配中括号中任意一个字符
res="[h,n]"
s="hello python"
result=re.findall(res,s)
print(result)

 

#3\d:匹配数字

res="\d"
s="hello99 python1223"
result=re.findall(res,s)
print(result)

 

#4\D:匹配非数字,空格也占一个字符
res="\D"
s="hello99 python1223"
result=re.findall(res,s)
print(result)

 

#5\s(小写):匹配空白(tab  空格)
res="\s"
s="hello99 python1223"
result=re.findall(res,s)
print(result)

 

#6\S(大写):匹配非空白
res="\S"
s="hello9 python3"
result=re.findall(res,s)
print(result)

 

#7\w(小写):匹配非特殊字符(字符、数字、汉字、_

res="\w"

s="hello9_ python3"

result=re.findall(res,s)

print(result)

 

#8\W(大写):匹配特殊字符(%#-)
res="\W"
s="hello9_ python3-@"
result=re.findall(res,s)
print(result)

 

2、多字符匹配
元字符
* :匹配前一个字符出现0次,或者无限次【贪婪模式】

#1* :匹配前一个字符出现0次,或者无限次【贪婪模式】
res="h*"
s="hello9_ python3-@"
result=re.findall(res,s)
print(result)

 

#2+:匹配前一个字符出现1次或无限次【贪婪模式,1--无限次】

res="h+"
s="hhello9_ python3-@"
result=re.findall(res,s)
print(result)

 

#3?:匹配前一个字符出现0次或者1次【非贪婪模式】
res="https?"
s="httpello9_ python3-@"
result=re.findall(res,s)
print(result)

 

res="https?"
s="httpsello9_ python3-@"
result=re.findall(res,s)
print(result)

 

#4{}:匹配前一个字符连续出现n
res="https{2}"
s="httpsello9_ python3-@"
result=re.findall(res,s)
print(result)

 

res="https{2}"
s="httpsssello9_ python3-@"
result=re.findall(res,s)
print(result)

 

#5{n,m}:匹配前一个字符连续出现nm区间的次数。

res="https{1,1}"
s="httpsssello9_ python3-@"
result=re.findall(res,s)
print(result)

 

res="https{1,3}"
s="httpsssello9_ python3-@"
result=re.findall(res,s)
print(result)

 

# $:匹配字符串结束位置
res=" hh$ "
s="hello python3-@"
result=re.findall(res,s)
print(result)

 

res="@$"
s="hello python3-@"
result=re.findall(res,s)
print(result)

 

# 5、分组匹配
# ():只匹配括号里面的
res="#mobile_phone#"
s="{'moblie_phone':'#mobile_phone#','pwd':'A123456'}"
result=re.findall(res,s)
print(result)

 

res="#(mobile_phone)#"
s="{'moblie_phone':'#mobile_phone#','pwd':'A123456'}"
result=re.findall(res,s)
print(result)

# ():只匹配括号里面的
# .: 匹配任意字符,除\n以外
# \w(小写):匹配非特殊字符(字符、数字、汉字、_
# +:匹配前一个字符出现1次或无限次【贪婪模式,1--无限次】
# ?:匹配前一个字符出现0次或者1次【非贪婪模式】

res="#(\w.+?)#"

s="{'moblie_phone':'#mobile_phone#','pwd':'A123456'}"
result=re.findall(res,s)
print(result) 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值