Bob Johnson
Bob Johnson

Reputation: 45

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

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

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}

Upvotes: 2

Views: 411

Answers (2)

The fourth bird
The fourth bird

Reputation: 163217

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

Upvotes: 2

pguardiario
pguardiario

Reputation: 54984

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/

Upvotes: 0

Related Questions