Search code examples
.netregexzero

match zeros including decimals with RegEx .NET


I have a textbox that accepts up to 7 characters. I need to make sure the value isn't accepted if it is all zeros before and/or after the decimal place, but i can't figure out the pattern

e.g 000, 00.000, 0.0000 etc.

cases such as 0.001, 0.1 etc can be allowed

have tried ^[0] but this didnt allow for single zero, or didnt allow for combinations such as 0.001


Solution

  • ^(?=.*[1-9])\d+(\.\d+)?$
    

    This regex will accept strings meeting the following conditions:

    • There must be a digit from 1-9 in the string - (?=.*[1-9])
    • It must begin with one or more digits - \d+
    • It may optionally end with a period and one or more digits - (\.\d+)?

    It will match these strings:

    • 42
    • 42.42

    It will not match these strings:

    • 0
    • 0.0
    • 42.
    • .42

    See it in action here.