1

Hello guys I'm trying to match the following regex:

  • Minimum characters: 8
  • Maximum characters: 22
  • Minimum uppercase letters: 1
  • Minimum lowercase letters: 1
  • Minimum digits: 2
  • Special characters are allowed
  • First character must be a letter
  • Maximum consecutive identical characters: 2

I've manage to complete every condition but the consecutive ones with:

(?=^.{8,22}$)(?=(.*\d){2})(?=(.*[A-Z]))^[a-zA-Z].*$

Following the post RegEx No more than 2 identical consecutive characters and a-Z and 0-9 I've seen that the way of not matching exact characters is:

((.)\2?(?!\2))+

But I'm unable to mix them both and have the full matching result. The tries are being done here: https://regex101.com/r/94KaXO/1/ where the first string should match but not the second one.

Thanks in advance.

Sergio González
  • 142
  • 2
  • 12

1 Answers1

2

You can use

^(?=.{8,22}$)(?!.*(.)\1{2})(?=(?:\D*\d){2})(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])[a-zA-Z].*$

See the regex demo.

Details:

  • ^ - start of string
  • (?=.{8,22}$) - 8 to 22 chars other than line break chars are allowed in the string
  • (?!.*(.)\1{2}) - no 3 consecutive identical chars allowed anywhere after zero or more chars other than line break chars as many as possible
  • (?=(?:\D*\d){2}) - there must be at least 2 not necessarily consecutive digits in the string
  • (?=[^A-Z]*[A-Z]) - there must be at least one uppercase letter in the string
  • (?=[^a-z]*[a-z]) - there must be at least 2 one lowercase letter in the string
  • [a-zA-Z] - a letter
  • .* - zero or more chars other than line break chars, as many as possible
  • $- end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Thanks @Wiktor. Can you give me a brief explanation of what did you changed and why? Thanks – Sergio González Jun 25 '21 at 09:59
  • @SergioGonzález The *no 3 consecutive identical chars allowed* lookahead (`(?!.*(.)\1{2})`) is what you were missing. Note the [principle of contrast](https://www.rexegg.com/regex-style.html#contrast), too. – Wiktor Stribiżew Jun 25 '21 at 10:00