Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for 0 or a positive number

Tags:

c#

regex

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.

like image 822
ktconrad90 Avatar asked Jun 19 '15 17:06

ktconrad90


2 Answers

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})$
like image 165
Anonymous Avatar answered Oct 05 '22 13:10

Anonymous


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   
     }
}
like image 40
Jonesopolis Avatar answered Oct 05 '22 13:10

Jonesopolis