Search code examples
pythonregexpasswords

How to test a regex password in Python?


Using a regex in Python, how can I verify that 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"

Solution

  • 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.