Python模块-re模块实例
正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在Python中)它内嵌在Python中,并通过 re 模块实现。
import re
-
\w与\W
- \w匹配字母数字及下划线
re.findall('\w','hello world 2022_04/24') ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', '2', '0', '2', '2', '_', '0', '4', '2', '4']
- \W匹配非字母数字下划线
re.findall('\W','hello world 2022_04/22') [' ', ' ', '/']
-
\s与\S
- \s匹配任意空白字符,等价于[\t,\n,\r,\f]
re.findall('\s','hello world 2022_04/22') [' ', ' ']
- \S匹配任意非空字符
re.findall('\S','hello world 2022_04-24') ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', '2', '0', '2', '2', '_', '0', '4', '-', '2', '4']
-
\d与\D
- \d匹配任意数字
re.findall('\d','hello world 2022_04-24') ['2', '0', '2', '2', '0', '4', '2', '4']
- \D匹配任意非数字
re.findall('\D','hello world 2022_04-24') ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', '_', '-']
-
\A与\Z(仅匹配位置,并不真正匹配文本)
- \A匹配字符串开始
re.findall('\Ah','hello world 2022_04-24') ['h']
- \Z匹配字符串结束,如果存在换行,只匹配到换行前的结束字符串
re.findall('24\Z','hello world 2022_04-24') ['24']
-
^与$等价于\A与\Z(仅匹配位置,并不真正匹配文本)
- ^
re.findall('^he','hello world 2022_04-24') ['he']
- $
re.findall('24$','hello world 2022_04-24') ['24']
-
重复匹配:| . | * | ? | .* | .*? | + | {n,m} |
.
中间只匹配一个字符,可以为空
re.findall('o.w','leeleeeeeleeo worleee ') ['o w']
*
左侧字符0或无数个
re.findall('ll*','leeleeeeeleeo worleee ') ['l', 'l', 'l', 'l']
?
左侧字符0个或1个
re.findall('el?','leeleeeeeleeo worleee ') ['e', 'el', 'e', 'e', 'e', 'e', 'el', 'e', 'e', 'e', 'e', 'e']
+
左侧字符1个或无穷个
re.findall('ll+','leeleeeeeleeo worleee ') []
{n,m}
左侧字符最少重复n次,最多m次
re.findall('le{2,4}','leeleeeeeleeo worleee ') ['lee', 'leeee', 'lee', 'leee']
.*
默认全部匹配
re.findall('l.*l','leeleeeeeleeo worleee ') ['leeleeeeeleeo worl']
.*?
re.findall('l.*?l','leeleeeeeleeo worleee ') ['leel', 'leeo worl']
-
re模块方法简析
-
compile
将正则表达式编译成 Pattern 对象
接着就可以用pattern对象进行匹配了,需要跟findall(), search(), match()搭配使用 -
findall
全部匹配,并把匹配出来的字符做成列表(如下图所示)
-
match
从头开始匹配的(决定是否在字符串刚开头的位置匹配) 如果匹配不到就会返回None 并且匹配到一个就返回后面就不会匹配了(如下图所示)
match和search一旦匹配成功,就是一个match object对象
-
search
和match()差不多,不同的就是可以不从0开始匹配(字符串内查找模式匹配),匹配一个结果就结束(如下图所示)
match和search一旦匹配成功,就是一个match object对象
-
split
根据正则匹配分割字符串,返回分割后的一个列表
-
sub
替换匹配成功的指定位置字符串
-
-
测试密码实例
''' 测试密码强度: 1.不能以_开头 2.有大写字母 3.有小写字母 4.有数字 5.长度在6-12之间 6.有特殊字符,只能是! @ # $ % ^ & * () _ + ? > < . , / {} ''' import re while True: tes_num = input('请输入密码:') if len(tes_num)<6:print('密码太短!') elif len(tes_num)>12:print('密码太长!') else: tes_parten = re.compile('(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%^&*()_+?><.,/{}])(^[A-Za-z0-9])') if re.search(tes_parten,tes_num):break else:print('密码强度不够!')
- (?=.*[A-Z])
.*
表示密码中可以包含多个字符,[A-Z]代表密码中需要包含至少一个大写字母
注意一定不要去掉.*
写成(?=[A-Z]),那样表示密码只能由一个字符组成,该字符是大写字母
- (?=.*[A-Z])