一、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}:匹配前一个字符连续出现n与m区间的次数。
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)



