0

I am new to using regex and use Python, and to gain some practice I thought I should write a program that would simulate checking conditions for a username and password. The password requirements I want are:

# 1. have one or more special characters
# 2. have one or more lowercase letters
# 3. have one or more uppercase letters
# 4. have one or more numbers

But the variable I came up with...

req_characters = r"([@#$%&*-_/\.!])+([a-z])+([A-Z])+([0-9])+"

and the regex search function...

    elif not re.search(req_characters, string):
    print("Your password must contain at least one uppercase and one 
           lowercase letter, one number, and one special character.")

results in strings that should match, triggering that if statement. Specifically, if I enter the string

#This_is_stuff0123

I get the print statement, so the regex thinks the conditions haven't been met. However, if I enter the string

##azAZ01

it matches, which tells me the regex will only take those character classes/groups in order. I tried various groupings with parentheses to no avail, and then tried using "or" in the following way, with the same result:

req_characters = r"([@#$%&*-_/\.!]|[a-z]|[A-Z]|[0-9]){6, 30}"

so I'm wondering what a simple solution might be to edit the current regex to achieve this result.

Emma
  • 27,428
  • 11
  • 44
  • 69

1 Answers1

0

I'm not quite sure, if this expression might match all your inputs, however it might help you to design an expression to do so:

 ^(?=.+[@#$%&*-_\/\.!])(?=.+[a-z])(?=.+[A-Z])(?=.+[0-9])[A-Za-z0-9@#$%&*-_\/\.!]{6,30}$

enter image description here

Code:

import re

string = 'A08a^&0azA'
# string = 'A08a^&0azAadA08a^&0azAadA08a^&0azAad'
matches = re.search(r'^((?=.+[@#$%&*-_\/\.!])(?=.+[a-z])(?=.+[A-Z])(?=.+[0-9])[A-Za-z0-9@#$%&*-_\/\.!]{6,30})$', string)
if matches:
    print(matches.group(1)+ " is a match")
else: 
    print('Sorry! No matches! Something is not right! Call 911')

Output

A08a^&0azA is a match

Graph

enter image description here

Emma
  • 27,428
  • 11
  • 44
  • 69