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]$')
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With