Reputation: 121
I'm looking for a regex to validate if numbers are below 20 000. I can't find the right solution, I have so far this:
(^([1-9]([0-9]{0,3})|20000)$)
Which works quite ok but as soon as it gets to 10 000 it gives no matches. So I have a gap from 9 999 - 20 000.
What am I doing wrong? I don't use regex for these situations, but the 3th party program required regex for such..
Thanks!
Upvotes: 3
Views: 906
Reputation: 477240
The ([1-9]([0-9]{0,3})
part is designed to match all numbers strictly below 2000
but you define it as: "A digit one to nine followed by zero to three digits". Now 10 000
is a one followed by four zeros: you can rewrite the part as:
[1-9][0-9]{3}|1[0-9]{4}
The full regex is now:
^[1-9][0-9]{3}|1[0-9]{4}|20000$
Upvotes: 2
Reputation: 627145
Your regex - ^([1-9]([0-9]{0,3})|20000)$
- matches numbers from 1
till 9999
and 20000
.
You may use
^([1-9]\d{0,3}|1\d{4}|20000)$
See demo
Breakdown:
^
- match start of string([1-9]\d{0,3}|1\d{4}|20000)
- match one of the alternatives:
[1-9]\d{0,3}
- 1
to 9
followed with 0 to 3 any digits (from 1
till 9999
)1\d{4}
- 1
followed with any 4 digits (to match 10000 - 19999
)20000
- literally 20000
$
- match the end of stringUpvotes: 2
Reputation: 29451
I've got this:
^([01]?\d{0,4}|20000)$
Which match any number from 0 to 20 000 and allow the user to use number with leading 0 Live Demo
Upvotes: 2