使用正则表达式强制执行密码



>我正在使用正则表达式来检查/强制执行密码要求 - 最少:6 个字符,最多:12 个字符,由数字、字母和指定的特殊字符组合而成。

import re
pswd = input('Please enter your password: ')
reg = re.compile(r'[A-Za-z0-9@#$]{6,12}')
mat = re.match(reg, pswd)
if mat:
print(f"{pswd} is a valid password.")
else:
print("Please check password requirements")

当我测试2We3345它打印时:

2We3345 是有效的密码。

我的印象是 .match 需要整个字符串完全匹配正则表达式。我错过了什么吗?我尝试了.search方法,但没有骰子。

这是我的工作代码:

import re
pswd = input('Please enter your password: ')
reg = re.compile(r'^[A-Za-z0-9@#$]{6,12}$')
spec_reg = re.compile(r'[@#$]+')
pswd_mat = reg.search(pswd)
spec_mat = spec_reg.search(pswd)
if pswd_mat and spec_mat:
print(f"{pswd} is a valid password")
else:
print("Please check password requirements")

密码约束为:

1. 仅使用字母 a-z、A-Z、数字 (0-9( 和特殊字符 @#$ 2. 长度 6-12 个字符 3. 每个至少有一个(小写、大小写、数字和特殊字符。

溶液:

import re
# (?=...) is a positive lookahead which means the pattern must be in the following characters
# (?=.*[A-Z]) means upper case character must be ahead
# (?=.*[a-z]) means a lower case character must be ahead
# (?=.*/d)    means a digit (0-9) must be ahead
# (?=.*[@#$]) a special character must be ahead
# pattern to satisfy constraints
pattern = r"^(?=.*[A-Z])(?=.*[a-z])(?=.*d)(?=.*[@#$])[A-Za-z0-9@#$]{6,12}$"
prog = re.compile(pattern)
prog.match(password)  # non-null if valid password

测试

pwds = ["password", "passWord0#", "password0#", "PassWord#0", "PassWord#0/", "PassWord#0andmore", ]
print("n".join([f"{pwd} {True if prog.match(pwd) else False}" for pwd in pwds]))

输出

password False        # No upper case, numbers, or special
passWord0# True       # At least one of each
password0# False      # No upper case
PassWord#0 True       # At least one of each
PassWord#0/ False     # "/" is not an allowed character
PassWord#0andmore False  # More than 12 characters

您使用的密码与捕获组匹配,因为它以 6-12 个字符的序列开头,与A-Za-z0-9@#$中的任何一个匹配。

此外,re.match只检查字符串的开头。从文档中:

re.match(pattern, string, flags=0(

如果零个或多个字符在 字符串开头匹配正则表达式模式,返回 对应的匹配对象

请注意,超过 12 个字符的密码也会通过,在 6 个有效字符之后包含无效字符的密码也会通过。

要匹配整个字符串,请尝试以下正则表达式:

'^[A-Za-z0-9@#$]{6,12}$'

此外,请检查特殊字符,如下所示:

reg = re.compile(r'[@#$]')
mat = re.search(reg, pswd)
if mat:
# ...

最新更新