Reputation: 1
#!/usr/bin/env python3
import re
passRegex = re.compile(r'''(
.{8,} # 8 or more characters
[A-Z] # at least 1 A-Z char
[a-z] # at least 1 a-z char
[0-9] # at least 1 0-9 number
)''', re.VERBOSE)
def strong_password():
password = input("Enter a password: ")
match = passRegex.search(password)
if (not match):
print("Password not strong enough")
return False
else:
print("Password is strong")
return True
strong_password()
This is from the automate the boring stuff with python chapter 7. Can someone explain what I am doing wrong? For some reason my regex doesn't work as intended.
Here is the full question: Write a function that uses regular expressions to make sure the password string it is passed is strong. A strong password is defined as one that is at least eight characters long, contains both uppercase and lowercase characters, and has at least one digit. You may need to test the string against multiple regex patterns to validate its strength.
Upvotes: 0
Views: 505
Reputation: 11
Try to put your regex object inside the function that you defied. And pass the the password (input) to your function to.
Here, I did for mine
import re
# create a function isPasswordStrong
def isStrongPass(password):
# create the Regex object from re.compile
passwordRegex = re.compile(r"""
(?=.*[a-z]) # matching with char a to z (0 or more)
(?=.*[A-Z]) # matching with char A to Z (0 or more)
(?=.*[0-9]) # matching with digit from 0-9
.{8,} # must have at least 8 or more
""", re.VERBOSE)
passEvaluation = passwordRegex.search(password)
if passEvaluation != None: # if it is matched
return True # Return this
print('Enter your password: ')
password = input()
test = isStrongPass(password)
if test == True:
print('Your password is STRONG')
else:
print('Weak password')
Upvotes: 1
Reputation: 112
@Tim's answer does a great job of showing regex that works as intended, this answer will highlight specifically why your current pattern does not.
Regex is very specific about ordering. Let's walk through your regex.
.{8,}
matches any character up to 8 times.
[A-Z]
AFTER THAT, looks for a SINGLE uppercase letter.
[a-z]
AFTER THAT, looks for a SINGLE lowercase letter.
[0-9]
AFTER THAT, looks for a SINGLE 0-9 integer.
The ordering matters. The only thing your regex matches would be a password like so:
1234AbCdAa8
8 or more of any characters, followed by a single capital, then a single lower, then a number. Any string that doesn't match that pattern would not register as a match in your regex.
Upvotes: 0
Reputation: 521609
You intend to assert a series of password requirements, but your current regex is not actually making these assertions. One way to go here is to add a positive lookahead for each requirement:
passRegex = re.compile(r'^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$', re.VERBOSE)
Upvotes: 1