1

My question is NOT similiar to Regular expression to match numbers between 1-5000, because I have something else to check (no range, leading and no leading zeroes, etc.).

I have the following RegEx in an input check:

^[0-9]{1,4}$ 

This works for digits with 1-4 length.

Unfortunately I have to allow only these combinations:

  • One digit numbers 1-9 (no leading zeroes)
  • or two digits numbers 10-30 (no leading zeroes)
  • or four digits numbers 0001-9999 (with leading zeroes).

What RegEx do I need?

4
  • You need the or operator, |. Something like ^([0-9]{1,4}|foo|bar)$, where foo is two digits numbers 10-30 (no leading zeroes), and bar is four digits numbers 0001-9999 (with leading zeroes). If you could write the regex you've got, you can write those -- the | operator is all you're missing. Commented Oct 27, 2016 at 14:15
  • Try ^([1-9][0-9]?|[0-9]{4})$. I guess you need to skip the numbers from 100 to 999 altogether, right? And does 10-30 range is just an example, and you want the 2-digit numbers from 10 to 99 or really only up to 30 only? Commented Oct 27, 2016 at 14:16
  • Then try ^([1-9]|[12][0-9]|30|[0-9]{4})$ Commented Oct 27, 2016 at 14:22
  • Possible duplicate of Regular expression to match numbers between 1-5000 Commented Oct 27, 2016 at 14:26

1 Answer 1

1

Let's define subpatterns for your conditions:

One digit numbers 1-9 (no leading zeroes) - Use [1-9]
or two digits numbers 10-30 (no leading zeroes) - Use [12][0-9]|30
or four digits numbers 0001-9999 (with leading zeroes) - Use [0-9]{4}

So, the whole pattern should be built from those alternatives that should be anchored and grouped (so that the anchors were applied to the group)

^([1-9]|[12][0-9]|30|[0-9]{4})$ 

See the regex demo

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

1 Comment

As I can see, this perecisely solves my problem. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.