【发布时间】:2020-12-20 03:13:04
【问题描述】:
需要一个只允许 0 和负数的正则表达式。下面的表达式也允许正数。
^-?[0-9]\d*(\.\d+)?$
【问题讨论】:
标签: regex regex-group regexp-replace
需要一个只允许 0 和负数的正则表达式。下面的表达式也允许正数。
^-?[0-9]\d*(\.\d+)?$
【问题讨论】:
标签: regex regex-group regexp-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
【讨论】:
'0' 中的 '00cat'。正如您将立即看到的那样,问题在于锚点^ 仅适用于交替的第一部分,而$ 仅适用于交替的最后部分。拍脑袋,嗯?
我建议你用正则表达式匹配
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
【讨论】:
'00' 和 '-017',而我的则不匹配。