How to test a regex password in Python? How to test a regex password in Python? python python

How to test a regex password in Python?


import repassword = raw_input("Enter string to test: ")if re.fullmatch(r'[A-Za-z0-9@#$%^&+=]{8,}', password):    # matchelse:    # 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-codeBool 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 incompletehardCodedSetOfAllowedCharacters = 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