3

I am trying to write a regex that:

  • starts with a letter
  • contains one uppercase and one lowercase letter
  • contains one number
  • does not allow special characters
  • minimum 8 characters

So far I have the upper/lowercase conditions, the number and minimum character requirements set with the following regex:

 /^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9]).{8,}$/

My best guess at resolving the starts with a letter and does not allow special characters requirements are below. This regex seems to evaluate all input to false:

/^[a-zA-Z](?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9]).{8,}$/
NealR
  • 9,361
  • 54
  • 153
  • 287

1 Answers1

4

You need to put the lookaheads after ^ and put [a-zA-Z] right after them and quantify the rest with {7,}:

^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])[a-zA-Z][a-zA-Z0-9]{7,}$

See the regex demo.

Pattern details:

  • ^ - start of a string
  • (?=.*?[a-z]) - at least 1 lowercase ASCII letter
  • (?=.*?[A-Z]) - at least 1 uppercase ASCII letter
  • (?=.*?[0-9]) - at least 1 ASCII digit
  • [a-zA-Z] - an ASCII letter
  • [a-zA-Z0-9]{7,} - 7 or more ASCII letters or digits (\w also allows _)
  • $ - end of string.
Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476