2014-08-28 118 views
0

什么是javascript正则表达式来确定小数点后的数字是否仅为零,小数点后的零数是否大于二?Javascript正则表达式涉及小数点后的零

一些测试的情况:

8 -> false 
8.0 -> false 
8.00 -> false 
8.000 -> true 
8.0000 -> true 
8.00001 -> false 
+0

是否每个字符串包含一个数字是这样,或者这个天马行空的更大的文本? – hwnd 2014-08-28 22:25:38

+0

只有一个数字 - 请注意,如第一个测试案例所示,可能不需要小数点。 – Mark13426 2014-08-28 22:26:17

+0

你能告诉我们你试过的东西吗? – joews 2014-08-28 22:26:34

回答

3

基于把你的意见,如果0.000是合法的,你想要的小数点是大于二后拒绝复式前导零,只有零一起,下面应该为你工作。

/^(?!00)\d+\.0{3,}$/ 

说明

^   # the beginning of the string 
(?!  # look ahead to see if there is not: 
    00  # '00' 
)   # end of look-ahead 
\d+  # digits (0-9) (1 or more times) 
\.  # '.' 
0{3,} # '0' (at least 3 times) 
$   # before an optional \n, and the end of the string 

Live Demo

+0

谢谢。这很好。也许稍微改进就是拒绝像000.000这样的表达式(\ d +在小数点之前允许一个或多个零)当然,现在我想知道000.000是否是一个数字,但在我的情况下,您的正则表达式对我来说足够好。 – Mark13426 2014-08-28 22:42:19

+0

'0.000'会被视为比赛吗? – hwnd 2014-08-28 22:44:04

+0

是的,这将是一场比赛 – Mark13426 2014-08-28 22:44:41

0

这里是一个在字符串的末尾匹配到.然后3个或更多0的正则表达式。

/\.0{3,}$/ 
0

试试这个:

var pattern = /^\d+\.0{3,}$/; // Regex from @hwnd 

function checkDigits(digits) { 

    var result = pattern.test(digits); 

    return result; 
} 

alert(checkDigits("5.000")); //Returns true.