1

I would like to use regular expression to match only positive integers at least 2 but no more than 4 digits. I know that I can do that with this regex: ^\d{2,4}$

Now, I want to exclude 00, 000, 0000 and also leading zeros such as 02, 003, 0001. Any suggestion?

Thanks in advance.

Kiki
  • 75
  • 1
  • 1
  • 7

2 Answers2

2

You can impose restrictions using a lookahead anchored at the beginning:

^(?!0+)\d{2,4}$

See demo

The negative lookahead (?!0+) checks at the beginning of a string (as it is located right after the ^ anchor) if there are any 1 or more zeros (with 0+).

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

Maybe something like:

^[1-9]\d{1,3}$

The first part, [1-9] makes sure the first digit is not a 0, after that, any digits can follow, up to a maximum of 4 in total.

Gato
  • 671
  • 5
  • 15