首页 > 解决方案 > 正则表达式只允许小数和 0 中的负数

问题描述

需要一个只允许 0 和负数的正则表达式。下面的表达式也允许正数。

^-?[0-9]\d*(\.\d+)?$

标签: regexregex-groupregexp-replace

解决方案


我会在这里使用一个替代:

^(?:0(?:\.0+)?|-\d+(?:\.\d+)?)$

演示

^(?:                from the start of the input
    0(?:\.0+)?      match 0, or 0.0, 0.00 etc.
    |               OR
    -\d+(?:\.\d+)?  match a negative number, with optional decimal component
)$                  end of the input

推荐阅读