Javascript 正则表达式不工作

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

Javascript RegEx Not Working

javascriptregex

提问by mint

I have the following javascript code:

我有以下 javascript 代码:

    function checkLegalYear() {
        var val = "02/2010"; 

        if (val != '') {
           var regEx = new RegExp("^(0[1-9]|1[0-2])/\d{4}$", "g");

            if (regEx.test(val)) {
               //do something
            }
            else {
               //do something
            }
        }
    }

However, my regEx test always returns false for any value I pass (02/2010). Is there something wrong in my code? I've tried this code on various javascript editors online and it works fine.

但是,对于我通过的任何值,我的 regEx 测试总是返回 false (02/2010)。我的代码有问题吗?我已经在各种 javascript 编辑器在线试过这段代码,它工作正常。

回答by Pointy

Because you're creating your regular expression from a string, you have to double-up your backslashes:

因为您是从字符串创建正则表达式,所以必须将反斜杠加倍:

var regEx = new RegExp("^(0[1-9]|1[0-2])/\d{4}$", "g");

When you start with a string, you have to account for the fact that the regular expression will first be parsed as such — that is, as a JavaScript string constant. The syntax for string constants doesn't know anything about regular expressions, and it has its own uses for backslash characters. Thus by the time the parser is done with your regular expression strings, it will look a lot different than it does when you look at your source code. Your source string looks like

当您从字符串开始时,您必须考虑到正则表达式将首先被解析为这样的事实 - 即作为 JavaScript 字符串常量。字符串常量的语法对正则表达式一无所知,它对反斜杠字符有自己的用途。因此,当解析器处理完您的正则表达式字符串时,它看起来与您查看源代码时有很大不同。您的源字符串看起来像

"^(0[1-9]|1[0-2])/\d{4}$"

but after the string parse it's

但在字符串解析后它是

^(0[1-9]|1[0-2])/d{4}$

Note that \dis now just d.

请注意,\d现在只是d.

By doubling the backslash characters, you're telling the string parser that you want single actual backslashes in the string value.

通过将反斜杠字符加倍,您告诉字符串解析器您想要字符串值中的单个实际反斜杠。

There's really no reason here not to use regular expression syntax instead:

这里真的没有理由不使用正则表达式语法:

var regEx = /^(0[1-9]|1[0-2])\/\d{4}$/g;

edit— I also notice that there's an embedded "/" character, which has to be quoted if you use regex syntax.

编辑- 我还注意到有一个嵌入的“/”字符,如果您使用正则表达式语法,则必须引用该字符。