0

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}$)
2
  • 2
    You said "alpha numeric value with length 5" but your regex only allows numbers? Commented Oct 26, 2022 at 23:40
  • Corrected it now :) Commented Oct 26, 2022 at 23:50

2 Answers 2

4

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)

Sign up to request clarification or add additional context in comments.

Comments

0

here is one way about it

/^(0?\d{3}|[\D\d]{5})/

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.