Home > other >  How to write a better Regex with OR patterns in Javascript
How to write a better Regex with OR patterns in Javascript

Time:10-27

I need a regex which should validate a value which

  1. can be a 3 digit number OR
  2. can be a 4 digit number but the first digit should be 0 OR
  3. 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})/

https://regex101.com/r/s8Swc0/1

  • Related