regexzeronegative-number

Regex, positive or negative int not preceding by 0 or minus


I want to create a filter which checks if typed value is expected.
Allowed are negative and positive (without '+' sign) numbers not preceding by zero. Also negative sign itself is allowed.
Problem is I can do search of negative number but I don't know how to add condition to find also minus.
I've tried to use lookaheads and whole this mechanism, but I've failed.
OK: -, -10, -54, 66, 0, 1
NOK: +, +1, -010, 010


Solution

  • What about that:

    ^(?:(?:-?(?:[1-9]\d*)?)|0)$
    

    Regex 101 Demo

    Explanation:

    ^ start marker
    - literally matches - sign
    ? makes it optional
    ([1-9]\d*) start by non zero digit followed by optional digits
    ([1-9]\d*)? the question sign makes it optional
    |0 means or a single zero
    $ end marker