Home > Back-end >  Regex validate string contains letters and numbers regardless of special characters
Regex validate string contains letters and numbers regardless of special characters

Time:12-15

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 :/

CodePudding user response:

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")

CodePudding user response:

The following regex pattern should work

r"^.*[A-Za-z] .*\d .*$|^.*\d .*[A-Za-z] .*$"

Explanation:

  • ^.*[A-Za-z] .*\d .*$ : finds passwords with letters before numbers
  • ^.*\d .*[A-Za-z] .*$ : finds passwords with numbers before letters
  • | : use OR to find one sequence OR the other
  • .* : used to find 0 or more characters of any type at this position
  • [A-Za-z] : used to find 1 or more letters at this position
  • \d : used to find 1 or more numbers at this position
  • ^ and $ : start and end of line respectively

Regex101 Demo

  • Related