user3303066
user3303066

Reputation: 17

Regex for alphanumeric with special character (-) and allow only maximum of 4 numeric characers

I need help creating a regex that allows alphanumeric characters with one special character (-) and should restrict the numeric characters to maximum 4.

I have tried the following but it is not working:

^[0-9a-zA-Z,-]\d{0,4}$

Upvotes: 0

Views: 257

Answers (2)

Code Maniac
Code Maniac

Reputation: 37775

You can use this regex

^(?!(.*\d){5,})[a-z0-9-]+$

Explanation

  • ^ - Anchor to start of string.
  • (?!.*\d{5,}) - Condition to check more than 4 digit.
  • [a-z0-9-] - Matches a to z, 0 to 9, and - one or more time.
  • $ - Anchor to end of string.

Demo

Upvotes: 1

MarcoS
MarcoS

Reputation: 17721

^[a-zA-Z-]*[0-9a-zA-Z-]{0,4}[a-zA-Z-]*$

I don't know if I completely understood your requirements...
However, this javascript regexp pattern accepts any number of any case alphabetic characters (included the hyphen "-"), and at most 4 digits; all characters (alphabetics, hyphen, digits) can occurr in any order.

Upvotes: 0

Related Questions