Regex for combination of letters and number that is 5-30 letters long, has at least 4 capital letters, 2 lowercase and at least 1 number

Viewed 88

Hey guys I'm new to regex and I want to create 1 single regex that matches with texts that are

  • 5-30 letters long,
  • have no special characters,
  • have at least 4 capital letters,
  • have at least 2 lowercase letters and
  • at least 1 number.

Examples: should match

  1. https://stackoverflow.com/Abcde3FGhiDE/Zyx23 should match: Abcde3FGhiDE
  2. |a|b|c|AbcdEFGH123|456Ac should match: AbcdEFG123
  3. P A Abcde3FGhiDE Z H should match: Abcde3FGhiDE
  4. ZZ123!Abcde3FGhiDE!123 should match: Abcde3FGhiDE

Examples: no match

  1. <HeLLoWoRlD"123
  2. |A|b|c|D|E|F|1|
  3. NULLLLLLLLLLLLLLLLLLLLLLllll 1
  4. IAMoverTHELIMITTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT3

Please make it as concise as you can. My attempt (demo):

(?=(?:\d*[A-Za-z]))(?=(?:\S*?[A-Z]){4,}\S*?$)(?=(?:[a-zA-Z]*\d))[A-Za-z0-9]{5,30}
2 Answers

You might use

\b(?=(?:[a-z0-9]*[A-Z]){4})(?=(?:[A-Z0-9]*[a-z]){2})(?=[a-zA-Z]*[0-9])[A-Za-z0-9]{5,30}\b

Explanation

  • \b Word boundary
  • (?=(?:[a-z0-9]*[A-Z]){4}) Assert 4 uppercase chars A-Z
  • (?=(?:[A-Z0-9]*[a-z]){2}) Assert 2 lowercase chars a-z
  • (?=[a-zA-Z]*[0-9]) Assert a digits
  • [A-Za-z0-9]{5,30} Match any of the listed 5 - 30 times
  • \b Word boundary

Regex demo

5-30 letters long, has at least 4 capital letters, 2 lowercase and at least 1 number

This mignt not be the cleanest but:

/^(?=[a-ZA-Z\d]{5,30}$)(?=(.*[A-Z]){4})(?=(.*[a-z]){2}).*\d/
Related