import re
print("匹配单个字符与数字")
r'''
. 匹配换行符以外的任意字符
[0123456789] []是字符集合,匹配方括号中所包含的任意一个字符
[a-z] 匹配任意一个小写字母
[A-Z] 匹配任意一个大写字母
[0-9a-zA-Z] 匹配任意一个数字字母
[0-9a-zA-Z_] 匹配任意一个数字字母和下划线
[^0-9] 匹配除了数字以外的所有字符
[0-9] 匹配任意一个数字
[\d] 匹配数字同上
[\D] 匹配非数字字符,同[^0-9]
[\w] 匹配数字,字母和下划线效果同[0-9a-zA-Z_]
[\W] 效果同[^0-9a-zA-Z_]
[\s] 匹配任意的空白字符(空格,换行,回车,换页,制表),效果同[ \f\n\r\t]
[\S] 效果同[^ \f\n\r\t]
flage:标志位,用于控制正则表达式的匹配方式,值如下
re.I 忽略大小写
re.L 做本地识别
re.M 多行匹配,影响^和$
re.S 是.匹配包括换行符在内的所有字符
re.U 根据Unicose字符集解析字符,影响\w \W \b \B
re.X 使我们以更灵活的格式理解正则表达式
'''print(re.search("[0-9]","sunk is a good man 7"))print(re.search("[\d]","sunk is a good man 5"))print("锚字符")'''
^ 行首匹配,和[^]不一样
$ 行尾匹配
\A 匹配字符串开始,和^的区别是,\A只匹配整个字符串的开头,即使在re.M
模式下也不会匹配他行的行首
\Z 匹配字符串结束,和$的区别是,\Z只匹配整个字符串的结束,即使在re.M
模式下也不会匹配他行的行尾
\b 匹配一个单词的边界,也就是指单词和空格的位置
\B 匹配非单词边界
'''print(re.search("^sunk","sunck is a good man sunk"))print(re.search("sunk$","sunck is a good man sunk"))print(re.findall("^sunck","sunck is a good man\nsunck is a nice man", re.M))print(re.findall("\Asunck","sunck is a good man\nsunck is a nice man", re.M))print("________")print(re.search(r"er\b","never"))print(re.search(r"er\b","nerve"))print(re.search(r"er\B","never"))print(re.search(r"er\B","nerve"))print("匹配多个字符")'''
x、y、z均为普通字符
(xyz) 匹配小括号内的xyz(作为一个整体去匹配)
x? 匹配0个或1个x
x* 匹配0个或任意多个x(贪婪匹配)
x+ 匹配至少一个x
x{n} 匹配确定的n个x(n为非负整数)
x{n,} 匹配至少n个x
x{n, m} 匹配至少n个,至多m个x
x|y |表示或,陪陪是x或y
'''print(re.findall(r"(sunck)","sunck is a good man sunck is a nice man"))print(re.findall(r"[\d]+@[\w]+.[a-zA-Z]{3}","yuanbo1556183481@qq.com, wang2319974932@163.com"))#需求提取“sunck is a …… man”print(re.findall(r"^sunck.*man$","sunck is a good man sunck is a nice man"))print("特殊")'''
*?
+?
x?
最小匹配 通常都是尽可能多的匹配,可以使用这种方式解决贪婪匹配
(?:x) 类似(xyz)但不表示一个组
'''print(re.findall(r"^sunck.*?man$","sunck is a good man sunck is a nice man"))print(re.findall(r"sunck.*?man","sunck is a good man sunck is a nice man"))defcheckPhone(str):
pat = r"^1(([3578]\d)|(47))\d{8}$"
res = re.match(pat,str)return res
print(checkPhone("18338737355"))