Need a regex to match a variable length string of numbers that can't be all zeros
-
22-08-2019 - |
Question
I need to validate an input on a form. I'm expecting the input to be a number between 1 to 19 digits. The input can also start with zeros. However, I want to validate that they are not all zeros. I've got a regex that will ensure that the input is numeric and between 1 and 19 numbers.
^\d[1,19]$
But I can't figure out how to include a check that the entire string is not all zeros. I tried this
^(![0]{1,19})(\d[1,19])$
but it fails on 0000000000000000001 because it's allowing a variable number of zeros.
How do I check that the entire string is NOT zeros?
Thanks.
I'm trying to do this in a ASP.NET RegularExpressionValidator so I was hoping for a single expression. I have other options, so I'm not out of luck if this can't be done.
Solution
^(?!0+$)\d{1,19}$
OTHER TIPS
Just do a negative lookahead:
(?!^0+$)(^\d{1,19})
This works fine in Perl.
(?!0+$) is a lookahead directive. The ?! is the negative lookahead command to search for 1 or more 0's to the end of the string. If that matches, then the characters are consumed, leaving the regular digit search of \d{1,19}.
Boost Perl Regexp has a good discussion of perl regexp as recognized by Boost.
you don't need RegEx for that
ulong test;
string number = "1234567890123456789";
if (ulong.TryParse(number, out test) && (test < 9999999999999999999ul) && (test > 0))
Console.WriteLine(test);