-3

I would like to test if the input value meets the criterias:

  • at least one lower case letter
  • at least one upper case letter
  • at least one digit
  • at least one character that is non \w

It seems the regex I programmed only follows this specific order like: abCD99$%

But if I shuffled the sequence, the regex doesn't work anymore: CD99ab$%

Anyone knows what the problem is please? Cheers in advance.

import re

# Asks user for an input

print('Please enter a password for checking its strength:')

pwd = input('> ')

#Test the input to see if it is more than 8 characters

if not len(pwd) < 8:
    pwdRegex = re.compile(r'([a-z]+)([A-Z]+)([0-9]+)(\W+)')     #order problem
    if not pwdRegex.search(pwd) == None:
        print('Password OK.')
    else:
        print('Please make sure password fulfills requirements!')
else:
    print('Characters must not be less than 8 characters!')

3 Answers3

1

You need to make use of lookaheads to verify your requirements:

(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*\W)^.+$
  • (?=.*[a-z]) - make sure we have a lowercase char somewhere
  • (?=.*[A-Z]) - make sure we have an uppercase char somewhere
  • (?=.*[0-9]) - make sure we have a digit somewhere
  • (?=.*\W) - make sure we have a non-\w somewhere
  • ^.+$ - all the aforementioned requirements were met so lets capture the entire line
    • This piece can be omitted if you're just doing a pass/fail test and don't need to capture anything

https://regex101.com/r/HdfVXp/1/

MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
0

In your case, I think it could be a good solution to make your validation without regex:

def isGoodPassword(password):
  # contains upper and lower, digit and special char
  return (not password.islower()
         and not password.isupper()
         and any(c.isdigit() for c in password) 
         and any(not c.isalnum() for c in password))


isGoodPassword('hello') # False
isGoodPassword('Hello!') # False
isGoodPassword('Hello!1') # True
thibsc
  • 3,747
  • 2
  • 18
  • 38
-1

The https://pypi.org/project/password-strength/ package contains code to do this. If you are interested in how this is done rather than actually doing it you could read the source code.

Jon Guiton
  • 1,360
  • 1
  • 9
  • 11