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