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?

Community
  • 1
  • 1
Stefan Meyer
  • 889
  • 1
  • 9
  • 19
  • 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. – 15ee8f99-57ff-4f92-890c-b56153 Oct 27 '16 at 14:15
  • Try [`^([1-9][0-9]?|[0-9]{4})$`](https://regex101.com/r/BVC4YE/3). 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? – Wiktor Stribiżew Oct 27 '16 at 14:16
  • Then try [`^([1-9]|[12][0-9]|30|[0-9]{4})$`](https://regex101.com/r/BVC4YE/4) – Wiktor Stribiżew Oct 27 '16 at 14:22
  • Possible duplicate of [Regular expression to match numbers between 1-5000](http://stackoverflow.com/questions/39473119/regular-expression-to-match-numbers-between-1-5000) – Thomas Ayoub Oct 27 '16 at 14:26

1 Answers1

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

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563