【问题标题】:Looking for a REGEXP for a number upto two decimal places寻找最多两位小数的正则表达式
【发布时间】:2014-05-07 18:09:40
【问题描述】:

我正在尝试这个

/-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/

但这需要多于两位小数,并且它接受值“.00”

它应该接受以下值
100.00
00.00
0
100
10000000000.00
98173827827.82

它应该拒绝以下值 .00
10.098
87.89381938193819
9183983109.9283912
10.aa
adjbdjbdj

我是正则表达式的新手

PS:- 我正在尝试下面的 javascript 代码。 因此,请将表达式仅限于 javascript。

提前致谢

【问题讨论】:

    标签: javascript jquery regex pattern-matching


    【解决方案1】:

    这个应该做的:

    /^\d+(\.\d{1,2})?$/
    

    【讨论】:

    • 用于测试和很好的可视化这个正则表达式的作用 - debuggex
    【解决方案2】:

    我会这样做:

    /-?(?:\d{1,3}(?:,?\d{3})+)?(?:\.\d{1,2})?$/
    

    【讨论】:

      【解决方案3】:

      试试这个:

      if (/^\d+([,.]\d{1,2})?$/im.test(value)) {
              alert("ACCEPTED\n" + value);
          } else {
              alert("REJECTED\n" + value);
          }
      }
      

      JSFIDDLE EXAMPLE

      正则表达式解释

      ^\d+([,.]\d{1,2})?$
      
      Assert position at the beginning of a line (at beginning of the string or after a line break character) (line feed, line feed, line separator, paragraph separator) «^»
      Match a single character that is a “digit” (ASCII 0–9 only) «\d+»
         Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
      Match the regex below and capture its match into backreference number 1 «([,.]\d{1,2})?»
         Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
         Match a single character from the list “,.” «[,.]»
         Match a single character that is a “digit” (ASCII 0–9 only) «\d{1,2}»
            Between one and 2 times, as many times as possible, giving back as needed (greedy) «{1,2}»
      Assert position at the end of a line (at the end of the string or before a line break character) (line feed, line feed, line separator, paragraph separator) «$»
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-26
        • 2013-04-15
        • 2012-01-05
        • 1970-01-01
        相关资源
        最近更新 更多