Javascript Regex:验证double/float

eig*_*ode 4 javascript regex floating-point validation

这是我正在研究的模式:

var re = /(\d{1,2}\.(?=\d{1,2}))/;
Run Code Online (Sandbox Code Playgroud)

我想要返回的是一个或两个数字的数字(永远不会超过24,因为它是一段时间mgmt应用程序),可能会或可能不会跟随一个或两个小数点尾随数字,但不超过两个.

我不确定与前瞻混合的括号子串匹配.我猜对了并嵌套了它们.最后,如果我的语法没问题,我认为我唯一缺少的是如何建议模式可能有也可能没有前导数字,并且可能包含也可能不包含带有试验数字的小数.

如果您需要更多信息,请告诉我.

更新,示例:

我们只处理时间,而且不会超过一天内发生的时间.24将是最高的投入.

有效:

23.75
1.4 
1
0.5 
0
.2
Run Code Online (Sandbox Code Playgroud)

无效:

1.897
%#$#@$#
Words
other characters
Run Code Online (Sandbox Code Playgroud)

最新更新:

由于这是一个十进制,23.75的作品.我们不算几分钟,而是几小时.

另外,为了记录,我尝试使用方法和条件进行验证,并且在小数点后让字母通过.我决定采用正则表达式.

Flo*_*ris 12

如果"给定的任何数字将小于24",那么不需要单独测试,那么下面的表达式将起作用.

^\d{0,2}(\.\d{0,2}){0,1}$
Run Code Online (Sandbox Code Playgroud)

http://rubular.com/r/YDfHr5T5sQ

测试:

23.75             pass
1.4               pass
1                 pass
0.5               pass
0                 pass
.2                pass
1.897             fail
%#$#@$#           fail
Words             fail
other characters  fail
Run Code Online (Sandbox Code Playgroud)

说明:

^             start matching at the start of the string
\d{0,2}       look for zero to two digits
(   ){0,1}$   look for this next thing zero or one time, then the end of the string
\.\d{0,2}     match exactly one decimal followed by up to two digits
Run Code Online (Sandbox Code Playgroud)

注意 - 此正则表达式与"空字符串"匹配.如果有可能以某种方式进入这个表达式,你可能想要单独测试它...

在您的javascript中测试的简单代码:

var str = "12.345";
var m = str.match(/^\d{0,2}(?:\.\d{0,2}){0,1}$/);
var goodTime;
if (!m) {
    alert(str + " is not a good time");
}
else {
    goodTime = m[0];
    alert("found a good time: " + goodTime);
}
Run Code Online (Sandbox Code Playgroud)

注意 - 我对regex- 添加?:"十进制后的位"组进行了调整.这也就意味着"比赛,但没有捕捉"这样的结果将只返回匹配m[0],而不是组.34m[1].它实际上并不重要,因为我goodTime在m [0]中分配了值(但只有在它是一个好时机时).你可以在这里看到这个