问题描述
我有以下 javascript 代码:
I have the following javascript code:
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
}
}
}
但是,对于我通过的任何值,我的 regEx 测试总是返回 false (02/2010).我的代码有问题吗?我已经在各种 javascript 编辑器在线试过这段代码,效果很好.
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.
推荐答案
因为您是从字符串创建正则表达式,所以您必须将反斜杠加倍:
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");
当您从字符串开始时,您必须考虑到正则表达式将首先被解析为这样的事实 - 即作为 JavaScript 字符串常量.字符串常量的语法对正则表达式一无所知,它对反斜杠字符有自己的用途.因此,当解析器处理完您的正则表达式字符串时,它看起来与您查看源代码时有很大不同.您的源字符串看起来像
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
"^(0[1-9]|1[0-2])/d{4}$"
但是在字符串解析之后是
but after the string parse it's
^(0[1-9]|1[0-2])/d{4}$
注意 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.
这篇关于Javascript 正则表达式不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!