验证字符串在javascript中是否为非负整数

验证字符串在javascript中是否为非负整数,javascript,regex,validation,integer,Javascript,Regex,Validation,Integer,这是一个验证整数的解决方案。有人能解释一下这个逻辑吗。 这是完美的,但我不知道怎么做 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 $ // en

这是一个验证整数的解决方案。有人能解释一下这个逻辑吗。
这是完美的,但我不知道怎么做

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]和number only。

此正则表达式可能更好。
/^[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

说明:

/^(\+?\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
以下测试用例返回true:
-0
-0000
0
00000
+0
+0000
1
12345
+1
+1234
。 以下测试用例返回false:
-12.3
123.4
-1234
-1


注意:这个正则表达式不适用于用科学记数法编写的整数字符串。

我认为这个问题最好是对这个答案的评论……应该由@Karim自己回答。请注意,这个代码并不完全正确。例如,它验证一个字符串,如
000…(10000次)…000
,这几乎不是一个“数字”。这将在“0”上失败。