[英]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). 我需要一个正则表达式来检查一个字符串的值是'0',还是一个长度等于1到10的正数(也就是第一个数字不能为零的地方)。
I'm stuck, I can get the 0, but I can't get the positive number. 我被困了,我可以得到0,但我不能得到正数。
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. 这个reg exp看起来有点疯狂,我一直在尝试很多不同的东西,让它变得更加疯狂和疯狂。
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.