【问题标题】:validate a string is non-negative whole number in javascript在javascript中验证字符串是非负整数
【发布时间】:2018-02-27 09:45:54
【问题描述】:

这是一个验证整数的解决方案。谁能解释一下Karim's answer的逻辑。
这完美地工作,但我无法理解如何。

var intRegex = /^\d+$/;
if(intRegex.test(someNumber)) {
   alert('I am an int');
   ...
}

【问题讨论】:

  • 我认为这个问题最好是对该答案的评论......并且应该由@Karim本人回答。
  • 请注意,这段代码并不完全正确。例如,它会验证像000...(10,000 times)..000 这样几乎不是“数字”的字符串。

标签: javascript regex validation integer


【解决方案1】:

正则表达式:/^\d+$/

^ // beginning of the string
\d //  numeric char [0-9]
+ // 1 or more from the last
$ // ends of the string

当它们全部组合在一起时:

从字符串的开头到结尾有一个或多个数字 char[0-9] 并且只有数字。

【讨论】:

    【解决方案2】:

    查看正则表达式参考: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
    

    【讨论】:

      【解决方案3】:

      这个正则表达式可能更好/^[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”上失败。
      【解决方案4】:

      什么是非负整数?

      非负整数是“0 或正整数”。

      来源:http://mathworld.wolfram.com/NonnegativeInteger.html

      换句话说,您正在寻找验证一个非负整数。

      上面的答案是不充分的,因为它们不包括诸如-0-0000 之类的整数,从技术上讲,它们在解析后会变成非负整数。其他答案也不验证前面带有+ 的整数。

      您可以使用以下正则表达式进行验证:

      /^(\+?\d+|-?0+)$/
      

      Try it Online!

      说明:

      ^                   # 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-0000000000+0+0000112345+1、@9876543。 以下测试用例返回 false:-12.3123.4-1234-1

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-06
        • 1970-01-01
        • 2013-03-15
        • 2012-02-10
        • 1970-01-01
        • 2012-12-03
        • 2011-03-11
        相关资源
        最近更新 更多