Javascript 带有十进制的负数的Javascript正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7749627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:26:48  来源:igfitidea点击:

Javascript regular expression for negative Numbers with decimal

javascriptjquery

提问by Manikandan Thangaraj

I want to test for this input: [an optional negative sign] 2 digits [an optional . and an optional digit] like this:

我想测试这个输入:[一个可选的负号] 2 位数字 [一个可选的 . 和一个可选的数字] 像这样:

-34or -34.5333or 34.53333or 34in JavaScript

-34-34.533334.5333334JavaScript 中

This is what I came up with but it doesn't work!

这是我想出来的,但它不起作用!

/^(-)\d{2}(\.d\{1})$/

Can someone please help me?

有人可以帮帮我吗?

回答by Prince John Wesley

Try this regex:

试试这个正则表达式:

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

回答by gion_13

this regex matches any valid integer.

此正则表达式匹配任何有效整数。

/^0$|^-?[1-9]\d*(\.\d+)?$/

you can modify this to suite your needs :

您可以修改它以满足您的需求:

/^-?[1-9]\d{0,1}(\.[1-9]{1})?$/

this matches 2.1, 21.4, 3, 90...

这匹配 2.1, 21.4, 3, 90 ...

回答by Kai

Perhaps regex is notneeded.

也许正则表达式是没有必要的。

function validate(val){
    return isNaN(val)?false:(Math.abs(Math.floor(val)).toString().length==2);
}

回答by Srinivasan.S

This below simple html code will validate the +ve & -ve numbers of 2 digits plus optional minimum of 1 digit after decimal point.

下面这个简单的 html 代码将验证 +ve 和 -ve 2 位数字加上可选的最小小数点后 1 位数字。

JS Code:

JS代码:

    function validateNum() {
        var patForReqdFld = /^(\-)?([\d]{2}(?:\.\d{1,})?)$/;
        var value = document.getElementById('txtNum').value;

        if(patForReqdFld.test(value)) {
            alert('Valid Number: ' + value);
        } else {
            alert('Invalid Number: ' + value);
        }
    }

HTML Code:

HTML代码:

    <label>Enter Number:&nbsp;</label>
    <input type="text" id="txtNum" onBlur="validateNum()"/>

回答by Aziz Shaikh

Try this regex:

试试这个正则表达式:

/^-?[0-9]{2}(?:\.[0-9]+)?$/

回答by Ryan

Try this:

尝试这个:

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

回答by Simon Stender Boisen

You can use this regular expression:

您可以使用此正则表达式:

-?\d{2}[.]?\d*

回答by 3emad

what your regEx ( /^(-)\d{2}(.d{1})$/ ) does is:

您的正则表达式( /^(-)\d{2}(.d{1})$/ )的作用是:

Start with requiring the negative and then correctly your requiring two digits, then with the "." your requiring any character, you should strict it to the symbol with "\", and finally comes one digit.

从要求否定开始,然后正确地要求两位数,然后是“。” 您需要任何字符,您应该将其严格为带有“\”的符号,最后是一位数字。

correct example code would be:

正确的示例代码是:

var str = '-34.23';
pat=/^\-?\d{2}(\.(\d)*)?$/g;
str.match(pat);

More testable example: http://jsfiddle.net/GUFgS/1/

更多可测试的例子:http: //jsfiddle.net/GUFgS/1/

use the "?" after the group to make that match an option i.e (\.\d*)?

使用 ”?” 在组之后使匹配选项即 (\.\d*)?