Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match regex in any order

I want to check for complex password with regular expression.

It should have 1 number 1 uppercase and one lowercase letter, not in specific order. So i though about something like this:

m = re.search(r"([a-z])([A-Z])(\d)", "1Az")
print(m.group())

But i don't know how to tell him to search in any order. I tried to look on web but I didn't found something interesting, thanks for help.

like image 759
Or Halimi Avatar asked Sep 22 '13 14:09

Or Halimi


2 Answers

You could have tried looking for password validating regex, the site has a lot of them ;)

That said, you can use positive lookaheads to do that:

re.search(r"(?=.*[a-z])(?=.*[A-Z])(?=.*\d)", "1Az")

And to actually match the string...

re.search(r"(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{3}", "1Az")

And now, to ensure that the password is 3 chars long:

re.search(r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{3}$", "1Az")

A positive lookahead (?= ... ) makes sure the expression inside is present in the string to be tested. So, the string has to have a lowercase character ((?=.*[a-z])), an uppercase character ((?=.*[A-Z])) and a digit ((?=.*\d)) for the regex to 'pass'.

like image 175
Jerry Avatar answered Sep 28 '22 02:09

Jerry


Why not just:

if (re.search(r"[a-z]", input) and re.search(r"[A-Z]", input) and re.search(r"[0-9]", input)):
    # pass
else
    # don't pass
like image 39
Ibrahim Najjar Avatar answered Sep 28 '22 02:09

Ibrahim Najjar