Search code examples
pythonregexpasswordsregex-lookarounds

Regex validate string contains letters and numbers regardless of special characters


For password validation in Python, I need to make a regex, which validates that passwords contains both letters and numbers. I have this regex:

re.match(r"^[A-Za-z]+\d+.*$", password)

But if the password contains a special character, then it won't pass. So password for example "MyPassword6" will be ok but "MyPassword-6" not. Also it will not pass if number is on the beginning "6MyPassword".

How to validate a regex with mandatory letters and numbers regardless of their order and regardless of the presence of other special characters?

Thank you!!!

adding [~!@#$%^&()_-] didn't help and I can't find other solution :/


Solution

  • This regular expression uses two positive lookahead assertions (?=...) to ensure that the password contains at least one letter and at least one number. The .* symbol in each lookahead assertion means that any characters, including special characters and whitespace can be present in the password, as long as the letters and numbers are also present.

    import re
    
    # compile the regular expression
    regex = re.compile(r'(?=.*[a-zA-Z])(?=.*[0-9])')
    
    def is_valid_password(password):
        # Check if the password is valid
        return regex.search(password) is not None
    
    password = "@u2_>mypassw#ord123!*-"
    
    if is_valid_password(password):
        print("Valid password")
    else:
        print("Invalid password")