Sasha
Sasha

Reputation: 1570

Regex to match an amount range

I need a regular expression to match an amount in a range of 10 to 10000 (inclusive) So far I came up with something like this:

^(?:[1-9]\\d{0,3}?)$

But there are two problems with it:

I know using regular expression to match a range is not the greatest idea, but it has to be done this way.

Upvotes: 2

Views: 1788

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You can use

^([1-9][0-9]{1,3}|10000)$

See the regex demo

Pattern details:

  • ^ - start of a string
  • ([1-9][0-9]{1,3}|10000) - an alternation with 2 options:
    • [1-9][0-9]{1,3} - a digit from 1 to 9, followed with 1 to 3 any digits (the {1,3} is important to exclude matching 5 and all numbers up to 10), and it matches integer numbers from 10 till 9999 with no leading zeros.
    • | - or
    • 10000 - a 10000 number
  • $ - end of string

Upvotes: 2

fedorqui
fedorqui

Reputation: 289525

You can say something like:

^([1-9][0-9]{1,3}|10000)$

See it in a test: https://regex101.com/r/wK4bC6/6

This mathces either 10000 or [1-9][0-9]{0,3}, this second one being any number from 10 to 9999.

Upvotes: 1

Related Questions