简体   繁体   中英

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.

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})$

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   
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM