Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Regex: password must contain at least one uppercase letter and number

I am doing form validation for a password using Python and Flask. The password needs to contain at least one uppercase letter and at least one number.

My current failed attempt...

re.compile(r'^[A-Z\d]$')
like image 990
Erik Åsland Avatar asked Nov 07 '15 22:11

Erik Åsland


2 Answers

We can use the pattern '\d.*[A-Z]|[A-Z].*\d' to search for entries that have at least one capital letter and one number. Logically speaking there are only two ways that a capital letter and a number can appear in a string. Either the letter comes first and the number after or the number first and the letter after.

The pipe | indicates 'OR', so we will look at each side separately. \d.*[A-Z] matches a number that is followed by a capital letter, [A-Z].*\d matches any capital letter that is followed by a number.

words = ['Password1', 'password2', 'passwordthree', 'P4', 'mypassworD1!!!', '898*(*^$^@%&#abcdef']
for x in words:
    print re.search('\d.*[A-Z]|[A-Z].*\d', x)
#<_sre.SRE_Match object at 0x00000000088146B0>
#None
#None
#<_sre.SRE_Match object at 0x00000000088146B0>
#<_sre.SRE_Match object at 0x00000000088146B0>
#None
like image 148
Pierre L Avatar answered Sep 23 '22 07:09

Pierre L


Another option is to use a lookahead.

^(?=.*?[A-Z]).*\d

See demo at regex101

The lookahead at ^ start checks if an [A-Z] is ahead. If so matches a digit.

like image 31
bobble bubble Avatar answered Sep 20 '22 07:09

bobble bubble