3
votes

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,}$/
1
2 regex giants have posted their answers and I wonder who will win ...RomanPerekhrest
This is an FAQ. You have not done your homework.Tomalak
Can you provide a link? I searched SO for the problem specified in my post and did not find an adequate answer.NealR
This is more like a logical issue here, not any "FAQ". Besides, the "homework" was done well, since the efforts and the description of what is not working are provided. Not a dupe by all means.Wiktor Stribiżew

1 Answers

3
votes

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.