正则表达式,正整数或负整数前面不带 0 或负号

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

我想创建一个过滤器来检查是否需要键入的值。
允许前面不带零的负数和正数(没有“+”符号)。负号本身也是允许的。
问题是我可以搜索负数,但我不知道如何添加条件来查找负数。
我试过使用前瞻和整个机制,但我失败了。
确定:-、-10、-54、66、0、1
挪威克朗:+、+1、-010、010

那个呢:

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

Regex 101 Demo

解释:

^ 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

下面是正确的工作正则表达式:

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

它将涵盖所有测试用例

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

Demo

从可选的 - 开始,然后确保第一个数字不为 0,其余数字尽可能多。也只处理 0 的特殊情况。