简体   繁体   中英

Regex string for validating Decimal excluding zero

I have a function which creates Regex string for validating decimal.

public static string DecimalWithPlaces(int wholePart, int fractionalPart)
{
     return @"^-?[0-9]{0," + wholePart + @"}\.[0-9]{1," + fractionalPart + @"}$";
}

Could anyone let me know how can I excluding zero from this?

For example: "0", "0.0","0.00" etc should not be matched.

Thanks

Amy's right - examples would be good.

However, I'm going in blind.

Did you want to exclude all zeros, or just the value of zero?

To exclude zeros, try this and see what happens.

public static string DecimalWithPlaces(int wholePart, int fractionalPart)
{
    return @"^-?[1-9]{0," + wholePart + @"}\.[1-9]{1," + fractionalPart + @"}$";
}

To exclude the number zero... That's actually not a good check for regex. That's a value check.

In my books you should be using TWO validation steps on the value. One to check that it meets your precision/scale requirements as per your regex above, the second to then check it for nonzero value.

I do believe that using regex for the zero value thing is possible. But I strongly advise against it. That said, if you're committed to ignoring that reccomendation then you'll probably want to look into Negative Lookahead regex structures.

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