我正在设置服务器,我想使用复杂的密码。
在Python中使用正则表达式,如何验证用户密码为:
至少8个字符
必须限制于此,尽管没有特别要求:
大写字母:A-Z
小写字母:a-z
数字:0-9
任何特殊字符:@#$%^&+ =
import re
password = raw_input("Enter string to test: ")
if re.match(r'[A-Za-z0-9@#$%^&+=]{8,}', password):
# match
else:
# no match
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
class RegistrationForm(FlaskForm):
username = StringField('Username',
validators=[DataRequired(), Length(min=2, max=20)])
email = StringField('Email',
validators=[DataRequired(), Email()])
#password =
pattern = "^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$"
password = PasswordField('Password', validators=[DataRequired(), Length(min=2, max=20)])
if re.match(r'[A-Za-z0-9@#$%^&+=]{8,}', password):
print ("Valid password")
else:
print ("Password not valid")
我希望输出的密码有效或无效
答案 0 :(得分:1)
正则表达式对我来说似乎有点沉重。您可以只使用普通的字符串操作:
from string import ascii_lowercase, digits
punctuation = '@#$%^&+='
valid_characters = ascii_lowercase + digits + punctuation
def validate_password(password):
return len(password) >= 8 and set(password) <= set(valid_characters)