Reputation: 2901
I'm no regex expert but I've given it a go, here's what I've come up with:
^([1]*[1-9]00|1000|2000)$
The idea is to allow 100 to 2000 inclusive in steps of 100.
I've tested it manually. It (seems) to work, but is this the best solution? Can anyone see any glaring errors?
Appreciate feedback.
Upvotes: 1
Views: 430
Reputation: 29451
Your regex is valid, just notice that [1] == 1
. An alternative is:
^(1?[1-9]00|[12]000)$
See demo.
If you're using server side validation, prefer int manipulation instead of regex: if (myNumber >= 100 && myNumber <= 2000 && myNumber % 100 == 0)
example:
var random = new Random(100);
int myNumber;
for (int i = 0; i < 5000; i++)
{
myNumber = random.Next(0, 10000);
if (myNumber >= 100 && myNumber <= 2000 && myNumber % 100 == 0)
{
Console.WriteLine($"{myNumber} respect the conditions.");
}
}
Upvotes: 3
Reputation: 72266
First of all, a regex is not the best solution for such a task. Regexps are good to match arbitrary sequences of characters; you want to work with numbers and the programming language you use can probably help you more than a regex.
However, if you insist, your regex must much the integer numbers 100
, 200
... 900
, 1000
, 1100
... 2000
A regular expression that matches these numbers ends in 00
. The prefix matches the integer numbers from 1
to 9
, those of two digits that have 1
as their first digit and 20
.
Put together, the regexp is:
([1-9]|1[0-9]|20)00
The pieces:
( # start a group
[1-9] # match any digit between 1 and 9...
| # ... or ...
1[0-9] # ... match any 2-digit number that starts with 1
| # ... or ...
20 # match 20
) # end o the group
00 # match 00
Another regexp is:
(1?[1-9]|[12]0)00
It groups the values 1..20
in a different way.
(
1? # match 1 or nothing
[1-9] # match any digit between 1 and 9
| # ... or ...
[12]0 # match 1 or 2 followed by 0 (i.e. match 10 or 20)
)
00 # end with 00
1?[1-9]
matches the numbers between 1
and 19
except 10
. 10
and 20
are matched by [12]0
.
Upvotes: 1