这是验证整数的解决方案。有人可以解释一下卡里姆回答的逻辑吗?
这完美地工作,但我无法理解如何。
var intRegex = /^\d+$/;
if(intRegex.test(someNumber)) {
alert('I am an int');
...
}
这是验证整数的解决方案。有人可以解释一下卡里姆回答的逻辑吗?
这完美地工作,但我无法理解如何。
var intRegex = /^\d+$/;
if(intRegex.test(someNumber)) {
alert('I am an int');
...
}
正则表达式:/^\d+$/
^ // beginning of the string
\d // numeric char [0-9]
+ // 1 or more from the last
$ // ends of the string
当它们全部组合在一起时:
从字符串的开头到结尾有一个或多个数字 char[0-9] 和仅数字。
查看正则表达式参考:http ://www.javascriptkit.com/javatutors/redev2.shtml
/^\d+$/
^ : Start of string
\d : A number [0-9]
+ : 1 or more of the previous
$ : End of string
这个正则表达式可能更好/^[1-9]+\d*$/
^ // beginning of the string
[1-9] // numeric char [1-9]
+ // 1 or more occurrence of the prior
\d // numeric char [0-9]
* // 0 or more occurrences of the prior
$ // end of the string
还将针对预先用零填充的非负整数进行测试
非负整数是“0 或正整数”。
换句话说,您正在寻找验证一个非负整数。
上面的答案是不充分的,因为它们不包括-0和之类的整数-0000,从技术上讲,它们在解析后会变成非负整数。其他答案也不验证+前面的整数。
您可以使用以下正则表达式进行验证:
/^(\+?\d+|-?0+)$/
解释:
^ # Beginning of String
( # Capturing Group
\+? # Optional '+' Sign
\d+ # One or More Digits (0 - 9)
| # OR
-? # Optional '-' Sign
0+ # One or More 0 Digits
) # End Capturing Group
$ # End of String
以下测试用例返回真:-0, -0000, 0, 00000, +0, +0000, 1, 12345, +1, +1234. 以下测试用例返回 false:-12.3, 123.4, -1234, -1.
注意: 此正则表达式不适用于以科学记数法编写的整数字符串。