学习《Python编程快速上手》P136
问题链接: https://automatetheboringstuff.com/chapter7/
Strong Password Detection
Write a function that uses regular expressions to make sure the password string it is passed is strong. A strong password is defined as one that is at least eight characters long, contains both uppercase and lowercase characters, and has at least one digit. You may need to test the string against multiple regex patterns to validate its strength.
代码实现:
# Problem: Strong Password Detection
# The url of the problem: https://automatetheboringstuff.com/chapter7/
import re
def WordDetect(text):
# beyond the number and digital
NumDigRegex = re.compile(r'[^0-9a-zA-Z]')
# length larger than 8
LenRegex = re.compile(r'[0-9a-zA-Z]{8,}')
# both Ucase and Lcase
UcaseRegex = re.compile(r'[A-Z]')
LcaseRegex = re.compile(r'[a-z]')
# at least 1 digital
DigRegex = re.compile(r'[0-9]')
if NumDigRegex.search(text) != None:
print('only letter or digital allows')
return 'Not Pass'
elif LenRegex.search(text) == None:
print('length of password lower than 8')
return 'Not Pass'
elif UcaseRegex.search(text) == None:
print('At least one Ucase letter')
return 'Not Pass'
elif LcaseRegex.search(text) == None:
print('At least one Lcase letter')
return 'Not Pass'
elif DigRegex.search(text) == None:
print('At least one Digital')
return 'Not Pass'
return 'Pass'
# Enter the password
password = input('Enter a password:\n')
# Show the result
print('')
print(WordDetect(password))
运行示例:(1)
Enter a password:
abcjAbkc1
Pass
运行示例:(2)
Enter a password:
ajggjk1[]
only letter or digital allows
Not Pass