I need a regex which should validate a value which
- can be a 3 digit number OR
- can be a 4 digit number but the first digit should be 0 OR
- can be a alpha numeric value with length 5
I did this regex which seems to working but I believe there is a better way of writing this. This is my regex. Please suggest a better way
(^[0-9]{3}$)|(^0[0-9]{3}$)|(^[0-9a-zA-Z]{5}$)
CodePudding user response:
Using an optional 0
can make it shorter and also change to the alphanumeric in the end:
/^(?:0?\d{3}|[a-z\d]{5})$/i
See this demo at regex101 (pattern is already in delimiters with i
flag for ignoring case)
CodePudding user response:
here is one way about it
/^(0?\d{3}|[\D\d]{5})/