0

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.

  • 1
    _"I need a regex for a password validation"_ First and foremost you need a solution for a problem. Why do you want to write one super complex regex that will be extremely difficult to understand and modify? It has no benefit at all. It's far better to keep the rules separated. – a better oliver Mar 19 '22 at 20:01

1 Answers1

0

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:

https://stackoverflow.com/a/22944075/11407290

https://stackoverflow.com/a/37237468/11407290

GuilhermeMagro
  • 321
  • 1
  • 10