0

I tried this expression -

^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$

This regex will enforce these rules:

At least one upper case English letter, (?=.*?[A-Z])

At least one lower case English letter, (?=.*?[a-z])

At least one digit, (?=.*?[0-9])

At least one special character, (?=.*?[#?!@$%^&*-])

Minimum eight in length .{8,} (with the anchors)

How will be the regular expression for below requirement.

  • Passwords that are 13 characters or longer only require lower case letters
  • Passwords must contain at least 8 characters
  • Passwords between 8 and 13 characters require at least 3 of the following 4 categories of characters:
    • Uppercase letters
    • Lowercase letters
    • Numbers
    • Symbols
San Jaisy
  • 15,327
  • 34
  • 171
  • 290
  • 2
    Okay, now, why are you trying to tackle such a complex task with so much conditional logic with a single regular expression? there is a famous saying stating that "if you have a problem that you are trying to solve with regex, you have 2 problems now". Why don't you just use good old imperative programming for that? You know... `if (pass.length > 13) { checkPass13(pass) }`, etc. What I'm saying is regex is not a good solution for your problem – Nemoden Dec 03 '19 at 05:39
  • @Nemoden - sounds good – San Jaisy Dec 03 '19 at 05:43
  • @Nemoden +1. Anything else than regex will almost always be easier to reason about :) – jensgram Dec 03 '19 at 05:45
  • See [Reference - Password Validation](https://stackoverflow.com/q/48345922/3600709) – ctwheels Dec 03 '19 at 16:50

1 Answers1

0

While a single regex may not be the most readable / sane way to do this, it's actually rather straightforward:

^(?=.*?[a-z])(.{13,}|(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,12})$

I've simply added an alteration on the length so that 13+ chars merely requires [a-z] while 8-12 chars (one could omit the upper bound due to ordering) requires the full monty.

jensgram
  • 31,109
  • 6
  • 81
  • 98