在 Python 中使用正则表达式,我如何验证用户的密码是:
- 至少 8 个字符
- 必须限于但不特别要求:
- 大写字母:A-Z
- 小写字母:a-z
- 数字:0-9
- 任何特殊字符:@#$%^&+=
注意,所有字母/数字/特殊字符都是可选的。我只想验证密码长度至少为 8 个字符,并且仅限于字母/数字/特殊字符。如果用户愿意,则由用户选择更强/更弱的密码。 到目前为止,我所拥有的是:
import re
pattern = "^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$"
password = raw_input("Enter string to test: ")
result = re.findall(pattern, password)
if (result):
print "Valid password"
else:
print "Password not valid"
最佳答案
import re
password = raw_input("Enter string to test: ")
if re.fullmatch(r'[A-Za-z0-9@#$%^&+=]{8,}', password):
# match
else:
# no match
{8,}
表示“至少 8”。 .fullmatch
函数要求整个字符串匹配整个正则表达式,而不仅仅是一部分。
关于python - 如何在 Python 中测试正则表达式密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2990654/