Regex for allowing all other numbers like 1,10,15,90,92....etc except Zero?
Hi i have a senario where i have to prevent a field from entering zero by using Regex. But i have failed in creating the regex Can anybody help me in giving a correct regex?
What i have done is
^[1-9]\d{0,2}(\d*|(,\d{3})*)$
But this fails because it fails when a number contains zero like 340 i开发者_StackOverflow中文版s entered.
My senario is that the field must be able to accept all other integers except zero
How about this regex:
^[1-9][0-9]*$
String starts with 1 to 9 then has zero or more characters in 0 to 9.
It seems like regex might be overkill here. Why don't you try something like this:
int value;
if (Int32.TryParse(fieldString, out value))
{
if (value == 0)
{
// handle invalid value
}
}
This can be done with the pattern:
^(?![0,]+$)\d{0,2}(\d*|(,\d{3})*)$
Assuming you only want to accept positive integers. The pattern (?![0,]+$)
prevents the expression from matching if it contains only zeros and commas. The second part is from the original expression, and allows the original combination of digits and commas for other values.
I assuming you'll be converting the field entry into an int? If so why not just do:
if (int == 0)
{
//not valid
}
However I'd hazard a guess you're using some kind of validation library?
You can try this one:
^[+-]?0*[1-9]\d*$
It accepts optional sign (plus or minus), then any number of leading zeroes, then at least one non-zero digit followed by any number of digits. You can see it in action at RegExr.
精彩评论