问题描述
需要一个仅允许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+)?))$'
此匹配项:'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