javascript jQuery 正则表达式测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5126408/
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-10-25 16:03:24  来源:igfitidea点击:

jQuery regex test

javascriptjqueryregex

提问by Or Weinberger

I'm trying to validate a value against a regex to check if the number is either a decimal (with only 2 digits after the decimal point)/integer. The rest should be invalid.

我正在尝试针对正则表达式验证一个值,以检查该数字是否为小数(小数点后只有 2 位数字)/整数。其余的应该是无效的。

I used the suggested regex here: Simple regular expression for a decimal with a precision of 2

我在这里使用了建议的正则表达式: Simple regular expression for a decimal with precision of 2

But when I included it in my jquery regex function, it doesn't seem to work:

但是当我将它包含在我的 jquery regex 函数中时,它似乎不起作用:

    function checkRegexp( o, regexp, n ) {
        if ( !( regexp.test( o.val() ) ) ) {
            o.addClass( "ui-state-error" );
            updateTips( n );
            return false;
        } else {
            return true;
        }
    }

bValid = bValid && checkRegexp( o_buy, /\d+(\.\d{1,2})?/, "Buy field can only contain numbers, no currency please" );

What am I doing wrong?

我究竟做错了什么?

Thanks,

谢谢,

回答by Bergius

You'll probably want to make that regex a little more precise, /^-?\d+(\.\d{1,2})?$/. Otherwise, it'll only test that the string containsa number.

您可能想让该正则表达式更精确一点,/^-?\d+(\.\d{1,2})?$/. 否则,它只会测试字符串是否包含数字。

Edit: updated the regex to cover negative numbers.

编辑:更新正则表达式以涵盖负数。

回答by ChrisJ

What do you mean by “it does not seem to work”? I've just tested your example, and it works as intended.

“它似乎不起作用”是什么意思?我刚刚测试了你的例子,它按预期工作。

The sole problem is that you try to find the numeric pattern anywhere inside the string. It means that something like abc3.4defis accepted by your regexp.

唯一的问题是您试图在 string 内的任何位置找到数字模式。这意味着abc3.4def您的正则表达式接受了类似的东西。

However I suppose that you want the string to contain onlya decimal number? Then you have to add the ^and $symbols at the start and at the end, to tell testthat you want to match the entirestring. So the regexp becomes:

但是我想您希望字符串包含一个十进制数?然后您必须在开头和结尾添加^$符号,以test表明您要匹配整个字符串。所以正则表达式变成:

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

Was this your issue? If not, I may post a complete webpage that works OK for me, if it can be of any help to you.

这是你的问题吗?如果没有,我可以发布一个对我有用的完整网页,如果它对你有帮助的话。

回答by jordancpaul

I'm pretty sure you want to be using the following regex

我很确定您想使用以下正则表达式

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

The problem with what you have is that {1,2} matches between 1 to 2 digits after the decimal, but doesn't fail if there is more. This is expected behavior.

您所拥有的问题是 {1,2} 匹配小数点后 1 到 2 位数字,但如果有更多数字,则不会失败。这是预期的行为。