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 must contain at least one uppercase letter and at least one number.

My current failed attempt ...

re.compile(r'^[AZ\d]$') 
+5
source share
4 answers

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

Pipe | indicates "OR", so we will consider each side separately. \d.*[AZ] matches a number followed by a capital letter, [AZ].*\d matches any capital letter followed by a number.

 words = ['Password1', 'password2', 'passwordthree', 'P4', 'mypassworD1!!!', '898*(*^$^@%&#abcdef'] for x in words: print re.search('\d.*[AZ]|[AZ].*\d', x) #<_sre.SRE_Match object at 0x00000000088146B0> #None #None #<_sre.SRE_Match object at 0x00000000088146B0> #<_sre.SRE_Match object at 0x00000000088146B0> #None 
+9
source

Another option is to use lookahead .

 ^(?=.*?[AZ]).*\d 

See the demon in regex101

To the top ^ a check begins if [AZ] ahead. If it matches the number.

+3
source

Regular expressions do not have the And operator, so it’s quite difficult to write a regular expression that matches valid passwords when justice is determined by something And something else And something else.

But regular expressions have an OR operator, so just apply DeMorgan’s theorem and write a regular expression that matches invalid passwords:

all without numbers OR nothing without capital letters

So:

 ^([^0-9]*|[^AZ]*)$ 

If something matches this, then this is the wrong password.

0
source

To match a string containing at least one digit character, use:

 .*[0-9].* 

A similar regular expression is used to validate upper / lower case.

0
source

Source: https://habr.com/ru/post/1235434/


All Articles