ktconrad90
ktconrad90

Reputation: 187

Regular expression for 0 or a positive number

I need a regular expression to check that a string's value is either a '0', or a positive number with a length equal to 1 to 10 (also where the first digit cannot be zero).

I'm stuck, I can get the 0, but I can't get the positive number.

Here is what I have:

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

This reg exp looks a little crazy, I've been trying a lot of different things and making even more crazier and crazier.

Upvotes: 9

Views: 4178

Answers (2)

Jonesopolis
Jonesopolis

Reputation: 25370

offering the faster, non-Regex approach:

static void Main(string[] args
{
     string str = "12";

     long test;
     if(str.Length <= 10 
         && long.TryParse(str, out test)
         && test >= 0)
     {
        //valid   
     }
}

Upvotes: 3

Anonymous
Anonymous

Reputation: 12017

For a range of possibilities, you use a comma, not a hyphen.

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

However, your regex can be shortened to:

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

Upvotes: 8

Related Questions