寻找最多两位小数的REGEX

时间:2014-05-07 18:09:40

标签: javascript jquery regex pattern-matching

我正在尝试这个


        /-?(?:\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。

先谢谢

3 个答案:

答案 0 :(得分:3)

这个应该做的:

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

答案 1 :(得分:0)

我做的事情如下:

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

答案 2 :(得分:0)

试试这个:

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

JSFIDDLE EXAMPLE

REGEX EXPLANATION

^\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) «$»