我的密码要求是:
至少10个符号
至少一位数
至少一个大写字母
至少一个小写字母
仅限字母或数字
所以我想使用re模块来检查我的字符串输入:re.search(pattern, string)
。
我的模式应该是什么?
答案 0 :(得分:10)
是的,你可以通过正则表达式做到这一点。
^(?=.*?\d)(?=.*?[A-Z])(?=.*?[a-z])[A-Za-z\d]{10,}$
>>> import re
>>> m = re.compile(r'^(?=.*?\d)(?=.*?[A-Z])(?=.*?[a-z])[A-Za-z\d]{10,}$')
>>> m.match('43543fooR')
>>> m.match('43543fooRy')
<_sre.SRE_Match object; span=(0, 10), match='43543fooRy'>
>>> m.match('foobar7678A')
<_sre.SRE_Match object; span=(0, 11), match='foobar7678A'>
>>> m.match('foobar76(')
>>> m.match('fokhjf7645464644sresrtf')
>>> m.match('fokhjf764546M4644sresrtf')
<_sre.SRE_Match object; span=(0, 24), match='fokhjf764546M4644sresrtf'>
>>>
(?=.*?\d)
检查至少一位数(?=.*?[A-Z])
至少一个上层。(?=.*?[a-z])
至少一个小写。[A-Za-z\d]{10,}
匹配大写或小写或数字字符10次或更多次。这可确保匹配必须至少包含10个字符。答案 1 :(得分:2)
while True:
passw = input("password: ")
if len(passw)<10:
print ("not enough")
continue
if passw.isalpha():
print ("atleast 1 digit")
continue
if passw.islower():
print ("at least 1 uppercase")
continue
if pass.isupper():
print ("Do you even password?")
continue
else:
print ("Finally, you created a password that FBI using.")
输出;
>>>
password: a
not enough
password: asdasdasdasdasdadsadsadsads
atleast 1 digit
password: asdasdasdasdasdasdasdasdads1111
at least 1 uppercase
password: asASasdasdasdasdasdas111
Finally, you created a password that FBI using.
password:
使用if
语句,首先检查长度。然后检查是否有isalpha()
的任何数字。然后检查是否有islower()
的大写字母。您不需要regex
。
答案 2 :(得分:-4)
这是一篇类似的文章,回答了您的大部分问题How to test a regex password in Python?
您可能还会发现正则表达式食谱有用https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s19.html
现场演示:https://ideone.com/4PGlTu
import re
password = raw_input("Enter string to test: ")
atLeastTenCharacters = ".{10,}"
hasAtLeastTenCharacters = re.findall(atLeastTenCharacters, password)
if (not hasAtLeastTenCharacters):
print "Password should be at least 10 characters long!"
atLeastOneDigit = "[0-9]"
hasAtLeastOneDigit = re.findall(atLeastOneDigit, password)
if (not hasAtLeastOneDigit):
print "Password should have at least one digit!"
atLeastOneUpper = "[A-Z]"
hasAtLeastOneUpper = re.findall(atLeastOneUpper, password)
if (not hasAtLeastOneUpper):
print "Password should have at least one upper case character!"
atLeastOneLower = "[a-z]"
hasAtLeastOneLower = re.findall(atLeastOneLower, password)
if (not hasAtLeastOneLower):
print "Password should have at least one lower case character!"
specialCharacters = "[^A-Za-z0-9]"
hasSpecialCharacters = re.findall(specialCharacters, password)
if (hasSpecialCharacters):
print "Password should NOT have special characters!"
if (hasAtLeastTenCharacters and hasAtLeastOneDigit and hasAtLeastOneUpper and hasAtLeastOneLower and (not hasSpecialCharacters)):
print "\nValid password"
else:
print "\nPassword not valid"