day16re模块的使用
1.通配符:什么都可以代表,数字,字母,特殊字符一个点只代表一个符号
re.findall("^a..x","asadfgdhgxflg")^代表值从字符串的开头开始匹配 re.findall("a..x$","asadfgdhgxflgru$")$从结尾开始匹配 贪婪匹配 re.findall("d*","sdfaghhhjerwerwrt")*0到无穷次的重复 什么都没有也能匹配上, re.findall("d+","sdfaghhhjerwerwrt")+1到无穷次 ?最多能匹配一个 {}范围自己定 {0,}==* {0,1}==? 惰性匹配 ret=re.findall("www[oldboy baidu]","www.baidu") re.findall("x[yz]","xyuuzuu") ['xy','xz'] 起到或的作用 re.findall("q[a*z]","rweetyuq") re.findall("q[^a-z]","q234")#只要是a到z都匹配失败 re.findall("\([^()]*\)","12+(3434-5*(2-1))") \功能:进行转译,元字符变成普通字符,普通字符变得有意义 []:特殊:- ^ \
2.元字符:. ^ $ * + ? { } [ ] | ( )
import re ret=re.findall('a..in','helloalvin') print(ret)#['alvin'] ret=re.findall('^a...n','alvinhelloawwwn') print(ret)#['alvin'] ret=re.findall('a...n$','alvinhelloawwwn') print(ret)#['awwwn'] ret=re.findall('a...n$','alvinhelloawwwn') print(ret)#['awwwn'] ret=re.findall('abc*','abcccc')#贪婪匹配[0,+oo] print(ret)#['abcccc'] ret=re.findall('abc+','abccc')#[1,+oo] print(ret)#['abccc'] ret=re.findall('abc?','abccc')#[0,1] print(ret)#['abc'] ret=re.findall('abc{1,4}','abccc') print(ret)#['abccc'] 贪婪匹配
注意:前面的*,+,?等都是贪婪匹配,也就是尽可能匹配,后面加?号使其变成惰性匹配
ret=re.findall('abc*?','abcccccc')print(ret)#['ab']
3.元字符之字符集[]:
#--------------------------------------------字符集[] ret=re.findall('a[bc]d','acd') print(ret)#['acd'] ret=re.findall('[a-z]','acd') print(ret)#['a', 'c', 'd'] ret=re.findall('[.*+]','a.cd+') print(ret)#['.', '+'] #在字符集里有功能的符号: - ^ \ ret=re.findall('[1-9]','45dha3') print(ret)#['4', '5', '3'] ret=re.findall('[^ab]','45bdha3') print(ret)#['4', '5', 'd', 'h', '3'] ret=re.findall('[\d]','45bdha3') print(ret)#['4', '5', '3']
4.反斜杠后边跟元字符去除特殊功能,比如\.
反斜杠后边跟普通字符实现特殊功能,比如\d
\d 匹配任何十进制数;它相当于类 [0-9]。
\D 匹配任何非数字字符;它相当于类 [^0-9]。
\s 匹配任何空白字符;它相当于类 [ \t\n\r\f\v]。
\S 匹配任何非空白字符;它相当于类 [^ \t\n\r\f\v]。
\w 匹配任何字母数字字符;它相当于类 [a-zA-Z0-9_]。
\W 匹配任何非字母数字字符;它相当于类 [^a-zA-Z0-9_]
\b 匹配一个特殊字符边界,比如空格 ,&,#等
ret=re.findall('I\b','I am LIST') print(ret)#[] ret=re.findall(r'I\b','I am LIST') print(ret)#['I']
5.

浙公网安备 33010602011771号