正则表达式只允许小数和0的负数

问题描述

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

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

解决方法

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

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

Demo

^(?:                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
,

我建议您使用正则表达式

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

Start your engine!

此匹配项:'0''-0.123'-0.000'0.123'-17'-29.33'-29.00'

它不匹配:'00''-017''12''44.7'

Python的正则表达式引擎执行以下操作。

^                : match beginning of string
(?:              : begin non-capture group
  0              : match '0'
  |              : or
  -              : match '-'
    (?:          : begin a non-capture group
      0\.\d+     : match '0.' then 
      |          : or
      [1-9]\d*   : match a digit other than zero then 0+ digits
      (?:\.\d+)  : match '.' then 1+ digits in a non-capture group
      ?          : make the non-capture group optional
    )            : end non-capture group
)                : end non-capture group
$                : match end of string

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...