Regular expression that supports at least two of the four conditions

5

I'm writing a regular expression for validating a password.

I wanted to know the easiest way to make a regular expression accept at least two of these conditions:

  • Uppercase letters
  • Lowercase letters
  • Special Characters
  • Numbers
  • At this point, I have the following regular expression:

    "(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{4,20}";
    

    where:

    (?=.*\d) : Accept at least one number.
    (?=.*[a-z]) : Accept at least one lowercase letter.
    (?=.*[A-Z]) : Accept at least one uppercase letter. (?=.*[@#$%]) : Accept at least one symbol. < {4,20} : Password between 4 and 20 characters.

    The problem is that, in order for the password to pass in this validation process, the password must have mandatory one of these symbols. That is, a password must have a number, a lowercase letter, a capital letter and a symbol.

    What I want is for the password to respect two or more conditions .

    Example :

    • A password with a lowercase letter and a symbol is accepted (from encounter with both conditions).
    • A password with a lowercase letter, a capital letter, and a symbol is also accepted.
    • A lowercase password is not accepted.
    asked by anonymous 27.07.2017 / 17:55

    2 answers

    4

    This one works:

    ^(?!^([a-z]+|[A-Z]+|\d+|[\W_]+)$).{4,20}$

    Tests: link

    Upon entering the site, in the right-hand pane, a detailed explanation of the regex is also given.

    EDITED: I noticed some unnecessary things and simplified the expression. The test link has been updated.

        
    27.07.2017 / 18:53
    0

    Try this:

    (?:.*[a-z].*[^a-z])|(?:.*[A-Z].*[^A-Z])|(?:.*[0-9].*[^0-9])|(?:.*[^0-9A-Za-z].*[0-9A-Za-z])
    

    Explanation:

    • (?:.*[a-z].*[^a-z]) - Any string that has a digit somewhere followed by something other than a digit.

    • (?:.*[A-Z].*[^A-Z]) - Any string that has a symbol followed by something other than a symbol.

    As a symbol, we mean something that is neither a capital letter, nor a lowercase letter nor a digit.

    All these parts are joined with (?:.*[0-9].*[^0-9]) . That is, you have to fall into one of the above cases.

        
    27.07.2017 / 18:20