Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 820
jCuga Avatar asked Jun 07 '10 15:06

jCuga


People also ask

How does Python validate username and password?

import time complete = False user = [["username","password"],["username2","password2"]] while not complete: username = input("What is the username?") password = input("What is the password?") for n in len(user): if username == user[n][0]: print("Good!") if password == user[n][1]: print("User has been identified, ...


2 Answers

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.

like image 67
Amber Avatar answered Oct 10 '22 23:10

Amber


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;
}
like image 37
jmucchiello Avatar answered Oct 10 '22 22:10

jmucchiello