[英]Regex to allow all Numbers but not if only 0 in Javascript
I have been trying to figure out how to return true if any number but not if only 0 or contains any decimal .
我一直在试图找出如何返回真,如果有任何数字,但如果只有0或包含任何小数,则不会.
that is 那是
1 //true
23 //true
10 //true
0.2 //false
10.2 //false
02 //false
0 //false
I have made this regex so far and it's working fine but it also allows 0 which I don't want 到目前为止,我已经制作了此正则表达式,并且工作正常,但它也允许0我不想要的
/^[0-9]+$/.test(value);
I tried to search my best and tried these regex so far but failed 到目前为止,我一直努力搜索并尝试过这些正则表达式,但均失败了
/^[0]*[0-9]+$/
/^[0-9]+[^0]*$/
I am not good in regex at all. 我一点都不在正则表达式上。 Thank you anticipation. 谢谢您的期待。
You were close: /^[1-9][0-9]*$/
. 您接近了: /^[1-9][0-9]*$/
。
The leading [1-9]
forces the number to have a most-significant digit which is not 0
, so 0
will not be accepted. 前导[1-9]
强制数字具有不为0
的最高有效数字,因此将不接受0
。 After that, any digit can come. 之后,任何数字都可以输入。
Finally, a number containing .
最后,一个包含的数字.
is not accepted. 不被接受。
Use a negative lookahead at the start. 开始时使用负前瞻。
/^(?!0)\d+$/.test(value);
This regex won't match the string if it contain 0 at the start. 如果此正则表达式开头不为0,则不匹配该字符串。
There is no need for a regex. 不需要正则表达式。 Just make use of Number
function or +
unary operator to convert it into an actual number and see if it's less than 1
and greater than -1
只需使用Number
函数或+
一元运算符将其转换为实际数字,然后查看它是否小于1
且大于-1
value = +value; // it's now a number
var bool = value < 1 && value > -1; // less than 1 but greater than -1
function validateNumber(yournumber){
return (parseFloat(yournumber ) == parseInt(yournumber) && parseInt(yournumber))
}
此正则表达式将适用于除0以外的所有数字,但00将适用
/([0-9]{2,})|[1-9]/.test(value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.