Michael Aboryone
Michael Aboryone

Reputation: 101

Regular expression for uppercase, lowercase and number

My task is to validate a string that must contain at least one lowercase and uppercase character and at least one number. I don't have to check the length of this string.

I'm trying to do something like this:

from re import match


regexp = "^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])"
string_to_validate = input("Write string with uppercase/lowercase characters and numbers.")
if not match(regexp, string_to_validate):
    raive ValueError("You should use uppercase and lowercase characters with numbers in your string")

But it seems to me that there's an expression for this purpose that is much better than that one. Honestly, I don't even know what the symbol '^' at the beginning of the expression is used for.

Upvotes: 1

Views: 1761

Answers (1)

Timur Shtatland
Timur Shtatland

Reputation: 12347

It is more maintainable and more readable to break up the requirements into individual regexes, and to use re.search:

import re

strs = ['Bb2', 'Bb', 'b2', 'B2']
for s in strs:
    if not (re.search(r'[A-Z]', s)
            and re.search(r'[a-z]', s)
            and re.search(r'\d', s)):
        print(f'Input "{s}" must contain at least 1 uppercase letter, 1 lowercase letter and 1 digit.')
    else:
        print(f'Input "{s}" is OK')
# Input "Bb2" is OK
# Input "Bb" must contain at least 1 uppercase letter, 1 lowercase letter and 1 digit.
# Input "b2" must contain at least 1 uppercase letter, 1 lowercase letter and 1 digit.
# Input "B2" must contain at least 1 uppercase letter, 1 lowercase letter and 1 digit.

Upvotes: 2

Related Questions