正则强口令实例

时间:2023-03-09 07:33:11
<automate the boring stuff with python>  正则强口令实例

书中7.18的强口令实践题

写一个函数,它使用正则表达式,确保传入的口令字符串是强口令。强口令的定义是:

长度不少于8 个字符,同时包含大写和小写字符,至少有一位数字。

你可能需要用多个正则表达式来测试该字符串,以保证它的强度。

推荐写法1更接近书中多个正则的含义也更好理解,写法2参考网上零宽断言。

注意写法1的大小写匹配要分开,如果写为[a-zA-Z]则只会匹配大小写字符之一即可,不满足同时有大小写

 #! python3
# 7.18.1 强口令的定义是:长度不少于8 个字符,同时包含大写和小写字符,至少有一位数字。
#你可能需要用多个正则表达式来测试该字符串,以保证它的强度。 import re
passwd=str(input('enter a passwd: '))
re1=re.compile(r'.{8,}')
re2=re.compile(r'[a-z]')
re3=re.compile(r'\d+')
re4=re.compile(r'[A-Z]') #写法2
#re9=re.compile(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$') if re1.search(passwd) and re2.search(passwd) and re3.search(passwd) and re4.search(passwd):
#if re9.search(passwd):
print('passwd is strong enough')
else:
print('passwd need upper,lower,number and more than 8')