As my first Python project, I am trying to create a program that will have you enter a password and check if it meets the requirements using regex.
The password I used, "Apples20!", prompted the program to say that I was missing a special character, even though I have a !. Here is the code:
import re
print("""Please create a password. Your password must be at least 8 characters long,
contain at least 1 number and at least 1 special character.""")
password = input("password: ")
if len(password) < 8:
print("Make sure your password has at least 8 characters.")
elif re.search(r"[0-9]",password) is None:
print("Make sure your password has at least 1 number.")
elif re.search(r"[!~@#$%^&*()-_ =[]:;/]",password) is None:
print("Make sure your password has at least 1 special character.")
else:
print("Your password seems fine.")
I'm sure there are more efficient ways to write this type of program, but I would just like to understand how to make this work the way it should.
The examples of this password project I looked up online ended up confusing me more as a newbie, and I have been running in circles.
Any other tips would be greatly appreciated! Thanks.
CodePudding user response:
The problem are the brackets: []
they are interpreted as an empty capturing group within the capturing group. So currently you are searching for a pattern which has any of the special characters and an empty capturing group within it. This is why you have to escape characters which are also part of the regex syntax, with a backslash like this: \[\]
re.search(r"[!@#$%^&*()_ \-=\[\]{};':\"\\|,.<>\/?]", password)