【发布时间】:2014-03-27 04:31:05
【问题描述】:
我有一个使用正则表达式验证小数和自然数的表单,但我有一个问题,这不能验证空字段。我的正则表达式是这样的:
"^([0-9])+\.[0-9]|[0-9]$"
我该怎么做才能让这个正则表达式验证空字段?谢谢。
【问题讨论】:
标签: regex
我有一个使用正则表达式验证小数和自然数的表单,但我有一个问题,这不能验证空字段。我的正则表达式是这样的:
"^([0-9])+\.[0-9]|[0-9]$"
我该怎么做才能让这个正则表达式验证空字段?谢谢。
【问题讨论】:
标签: regex
使用这个正则表达式来处理数字(只有正数)和空。
^(?:[0-9]+(?:\.[0-9]+)?)?$
正则表达式的解释是:
NODE EXPLANATION
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
[0-9]+ any character of: '0' to '9' (1 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
[0-9]+ any character of: '0' to '9' (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
【讨论】:
$ 之前的?。最后是^(?:[0-9]+(?:\.[0-9]+)?)$,不允许有空。
你是这个意思吗?
"^(?:([0-9])+\.[0-9]*|[0-9]|)$"
这个正则表达式包含一个额外的没有字符的可能性。
【讨论】:
试试:
^([0-9]+\.[0-9]*|[0-9]*)$
这个:
【讨论】:
谢谢大家,
我证明了你所有的建议,但它根本没有解决我的问题, 仍然允许输入空白字段,我可能解释得不好, 我希望我的正则表达式不允许注册空字段。
【讨论】: