How to test a regex password in Python?
Using a regex in Python, how can I verify th开发者_JAVA百科at a user's password is:
- At least 8 characters
- Must be restricted to, though does not specifically require any of:
- uppercase letters: A-Z
- lowercase letters: a-z
- numbers: 0-9
- any of the special characters: @#$%^&+=
Note, all the letter/number/special chars are optional. I only want to verify that the password is at least 8 chars in length and is restricted to a letter/number/special char. It's up to the user to pick a stronger / weaker password if they so choose. So far what I have is:
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
The {8,}
means "at least 8". The .fullmatch
function requires the entire string to match the entire regex, not just a portion.
I agree with Hammish. Do not use a regex for this. Use discrete functions for each and every test and then call them in sequence. Next year when you want to require at least 2 Upper and 2 Lower case letters in the password you will not be happy with trying to modify that regex.
Another reason for this is to allow user configuration. Suppose you sell you program to someone who wants 12 character passwords. It's easier to modify a single function to handle system parameters than it is to modify a regex.
// pseudo-code
Bool PwdCheckLength(String pwd)
{
Int minLen = getSystemParameter("MinPwdLen");
return pwd.len() < minlen;
}
Well, here is my non-regex solution (still needs some work):
#TODO: the initialization below is incomplete
hardCodedSetOfAllowedCharacters = set(c for c in '0123456789a...zA...Z~!@#$%^&*()_+')
def getPassword():
password = raw_input("Enter string to test: ").strip()
if (len(password) < 8):
raise AppropriateError("password is too short")
if any(passChar not in hardCodedSetOfAllowedCharacters for passChar in password):
raise AppropriateError("password contains illegal characters")
return password
import re
password=raw_input("Please give me a password: ")
if len(re.findall("[A-Za-z0-9@#$%^&+=]",password))==len(password):
print("Great password")
else:
print("Incorrect password")
If you want to run it in python 3.0 and above change raw_input with input.
import re
password = input("Enter Password")
True if (re.fullmatch(r'^[A-Za-z0-9@#$%^&+=]{8,}$', password)) else False
if however you wanted to make the second bits required, you could do the following:-
True if (re.fullmatch(r'^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.[@#$%^&+=])[A-Za-z0-9@#$%^&+=]{8,}$', password)) else False
Note: [0-9] in python is a subset of \d so you might want to stick to [0-9] read the following post https://stackoverflow.com/a/6479605/4170558
If you wan the program to continuously run until a correct password is inputted do the following.
import re
while True:
print('Input a strong password.')
password = input()
if re.match(r'[A-Za-z0-9@#$%^&+=]{8,}', password):
print('Very nice password. Much secure')
break
else:
print('Not a valid password')
This regex validate if the password:
- uppercase letters: A-Z -lowercase letters: a-z
- numbers: 0-9
any of the special characters: !@£$%^&*()_+={}?:~[]]+
re.compile(r'^.*(?=.{8,10})(?=.*[a-zA-Z])(?=.*?[A-Z])(?=.*\d)[a-zA-Z0-9!@£$%^&*()_+={}?:~\[\]]+$')
But what if the user enters another special characters out of your list? Should you include all existing special characters? Another solution may be search what we expect to be in the password separately:
- numbers: 0-9
- lowercase letters: a-z
- uppercase letters: A-Z
- any special characters
- No white space
p = password
def is_valid(p):
if (len(p) >= 8 and
re.search(r'\d+', p) and
re.search(r'[a-z]+', p) and
re.search(r'[A-Z]+', p) and
re.search(r'\W+', p) and not
re.search(r'\s+', p)):
return True
else:
return False```
精彩评论