Reputation: 43
I'm trying to make a regex that matches the following criteria:
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
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 stringUpvotes: 3
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