Minghua
Minghua

Reputation: 43

Regular expression - starting with 3 alphanumeric characters which includes at least one letter and one number, and ending with a letter

I'm trying to make a regex that matches the following criteria:

  1. 4 characters.
  2. The beginning 3 characters must be alphanumeric characters, including at least one letter and one digit.
  3. The last character must be a letter.

So I expect the results would be:

I tested the following regex which matches criteria 2, but still cannot find a solution to match criteria 1&3.

^(?!.*[^a-zA-Z0-9])(?=.*\d)(?=.*[a-zA-Z]).{3}$

I tried this one but it failed on case2.

^(?!.*[^a-zA-Z0-9])(?=.*\d)(?=.*[a-zA-Z]).{3}[a-zA-Z]$

How can I combine these criteria? Thanks!

Upvotes: 2

Views: 4011

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

You may use

^(?=.{0,2}[0-9])(?=.{0,2}[a-zA-Z])[0-9a-zA-Z]{3}[a-zA-Z]$

See the regex demo

Details

  • ^ - start of string
  • (?=.{0,2}[0-9]) - there must be an ASCII digit after 0 to 2 chars
  • (?=.{0,2}[a-zA-Z])- there must be an ASCII letter after 0 to 2 chars
  • [0-9a-zA-Z]{3} - 3 ASCII alphanumerics
  • [a-zA-Z] - an ASCII letter
  • $ - end of string

Upvotes: 3

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

No need to use complicated features for 3 or 4 characters:

/^(?:[a-z0-9](?:[0-9][a-z]|[a-z][0-9])|[0-9][a-z]{2}|[a-z][0-9]{2})[a-z]$/i

or

/^(?:[a-z](?:[0-9][a-z0-9]|[a-z][0-9])|[0-9](?:[a-z][a-z0-9]|[0-9][a-z]))[a-z]$/i

Upvotes: 1

Related Questions