[英]How can I simply this number format validation regex?
So, I have this if statement:所以,我有这个 if 语句:
if (String(val).search(/^((\\d+(((\\,\\d{3,})+)?)(\\.\\d+)?)|(\\.\\d+))$/) !== -1)
Which says (as far as I am aware):其中说(据我所知):
The string must either start with at least one digit, or a .
该字符串必须至少以一位数字开头,或者以
.
. .
If the string starts with a digit there can optionally be commas in the string, as long as the commas are followed by at least three digits.如果字符串以数字开头,则字符串中可以有逗号,只要逗号后跟至少三位数字即可。 If the string has a
.
如果字符串有一个
.
in it, it must be followed by at least one digit.在其中,它必须后跟至少一位数字。
There can be only one .
只能有一个
.
So, strings like:所以,像这样的字符串:
5 5
5.00 5.00
5000 5000
5,000 5,000
5000.00 5000.00
5,000.00 5,000.00
Will all return true都会返回真
But strings that contain anything but 0-9 , .
但是包含
0-9 , .
任何内容的字符串0-9 , .
or are malformed will return false.或格式错误将返回 false。 so strings like this:
所以像这样的字符串:
5,00 5,00
5,00.00 5,00.00
5.00.00 5.00.00
a5 a5
Now, the above works, but I am wondering if there is any way to simplify it?现在,上述工作,但我想知道是否有任何方法可以简化它?
You can remove some redundant parenthesis:您可以删除一些多余的括号:
^(\d+((\,\d{3,})+)?(\.\d+)?|\.\d+)$
And something like (( ... )+)?
还有像
(( ... )+)?
can be replaced by: ( ... )*
, so the final regex might look like this:可以替换为:
( ... )*
,因此最终的正则表达式可能如下所示:
^(\d+(\,\d{3,})*(\.\d+)?|\.\d+)$
And if you'd like to reject input like:如果您想拒绝输入,例如:
50000,000,000.0
and only allow for:并且只允许:
5,000,000.0
50,000,000.0
500,000,000.0
Then do something like this:然后做这样的事情:
^(\d{1,3}(\,\d{3})*(\.\d+)?|\.\d+)$
I don't think you could simplify it, beyond stripping out a few parens, and as it is it's arguably not complex enough.我不认为你可以简化它,除了去掉几个括号,而且可以说它不够复杂。 The pattern will also allow malformed strings such as
该模式还将允许格式错误的字符串,例如
50000,000,000.000000000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.