I need a regex for a password validation the password must be: 8 characters in length, 2 upper,3lower,1 special character and 2 numbers
([A-Z]{2})([?!@#*%^&- ]{1})([0-9]{2})([a-z]{3})$ This is what I came up with but the problem is that it doesn't match at any order.
CodePudding user response:
Using lookaheads:
^(?=(?:.*[a-z]){3})(?=(?:.*[A-Z]){2})(?=.*[?!@#*%^&- ])(?=(?:.*\d){2})[a-zA-Z?!@#*%^&- \d]{8}$
Explanation:
^ // Assert is the beginning of the string
(?=(?:.*[a-z]){3}) // Positive lookahead to match exactly 3 lowercase letters
(?=(?:.*[A-Z]){2}) // Positive lookahead to match exactly 2 uppercase letters
(?=.*[?!@#*%^&- ]) // Positive lookahead to match exactly 1 special character
(?=(?:.*\d){2}) // Positive lookahead to match exactly 2 numbers
[a-zA-Z?!@#*%^&- \d]{8} // Assert that has exactly 8 of the defined characters
$ // Assert is the end of the string
Tests: RegExr
Other responses about Regex for knowledge: