tags:

views:

53

answers:

3

Hello guys,

I have the option to use a regex to validate some values and I would like to know the best way to do it.

I have several ranges (not in the same regex/validation) such as 1-9 (this is easy :P), and:

1-99 1-999 1-9999

Also, I need to check for leading zeros, so, 0432 is a possible match.

Any ideas?

I know that Regex might not be the best approach for this, but it's what I have, and it's part of a framework I have to use.

Tahnks

A: 

The easy way (n is the amount of numbers):

[0-9]{n}
Bobby
Hello Bobby. I tried this way. but sometimes I don't want the first 0.
George
A: 

I’m not 100% clear on what you want but perhaps something like this?

\d{1,2}

This is the equivalent to \d\d? and will match any one- or two-digit number, that is any number from 0 to 99, including leading zeros.

If you really want to exclude 0, then things get a lot more complicated.

Basically, you need to check for 1–9 and 01–09 explicitly. The third group of allowed numbers will have two digits that do not start with a zero:

0?[123456789]|[123456789]\d

Now the part before the | will check whether it’s a number below 10, with optional leading zero. The second alternative will check whether it’s a two-digit number not starting with a zero.

The rest of the ranges can be checked by extending this.

Konrad Rudolph
+1  A: 

There is a fundamental flaw with all other answers!!

bool isMatch = Regex.IsMatch("9999", @"\d{1,3}");

Returns true although the number is not a 1-3 digit number. That is because part of the word matches the expression.

You needs to use:

bool isMatch = Regex.IsMatch("9999", @"^\d{1,n}$");

Where n is the maximum number of digits.

UPDATE

In order to make sure it is not zero, change it to below:

bool isMatch = Regex.IsMatch("9999", @"(^\d{2,n}$)|[1-9]");

UPDATE 2 It still would not work if we have 00 or 000 or 0000. My brain hurts, I will have a look again later. We can do it as two expressions ("(^\d{2,n}$)|[1-9]" and NOT (0)|(00)|(000)|(0000)) but that probably is not accepted as a SINGLE regex answer.

Aliostad