Search code examples
regexdojo

Validation Regex to disallow a single digit 0


I've tried many examples to disallow a single digit 0. The closest one working is [^0] but that matches on 20, 30, etc. I only want to match on 0.


Solution

  • If you want to match not a zero but do want to allow positive and negative numbers you might use. This uses anchors ^ and $ to assert the start and the end of the string.

    ^[+-]?[1-9][0-9]*$

    Without using anchors you could use a word boundary \b:

    [+-]?\b[1-9][0-9]*\b

    That would match an optional plus or minus sign [+-]?, a digit from 1 - 9 [1-9] so it does not match a zero followed by zero or more times a digit [0-9]*