NealR
NealR

Reputation: 10709

Regex that starts with letter, contains one uppercase/one lowercase letter, one number and no special characters & min 8 characters

I am trying to write a regex that:

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,}$/

Upvotes: 3

Views: 2244

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627488

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.

Upvotes: 4

Related Questions