1

我有一个多文化网站,允许用户以 dd-MMM-yyyy 格式输入值。我能够根据 C# 中的文化确定不同的值(May,English = May,German = Mai)

我遇到的问题是这几个月的 javascript 验证。我能够建立可接受值的列表:

英语:

^Jan$|^Feb$|^Mar$|^Apr$|^May$|^Jun$|^Jul$|^Aug$|^Sep$|^Oct$|^Nov$|^Dec$

德语:

^Jan$|^Feb$|^Mrz$|^Apr$|^Mai$|^Jun$|^Jul$|^Aug$|^Sep$|^Okt$|^Nov$|^Dez$

我只是想让这个正则表达式不区分大小写。但是我看到的所有引用都指向 /gi 标志,但我所有的例子都没有意义。我尝试了以下方法,但它不起作用:

var shouldMatch = "may";
var regexPattern = "^Jan$|^Feb$|^Mar$|^Apr$|^May$|^Jun$|^Jul$|^Aug$|^Sep$|^Oct$|^Nov$|^Dec$/gi"
if(shouldMatch.match(regexPattern) != null) {
    //this should happen
}

我究竟做错了什么?用于 javascript 的正则表达式帮助正在杀死我。

4

5 回答 5

1

jsFiddle Demo

但是尝试匹配“mAR”或“MAr”等呢?这很快就变成了一个有趣的场景。在我看来,一个简单的方法就是匹配大写

var shouldMatch = "May";
var regexPattern = "^JAN$|^FEB$|^MAR$|^APR$|^MAY$|^JUN$|^JUL$|^AUG$|^SEP$|^OCT$|^NOV$|^DEC$";
if(shouldMatch.toUpperCase().match(regexPattern) != null) {
 alert("match");
}
于 2013-05-10T00:26:59.820 回答
1

您的正则表达式不应字符串:

var shouldMatch = "may";
var regexPattern = /^Jan$|^Feb$|^Mar$|^Apr$|^May$|^Jun$|^Jul$|^Aug$|^Sep$|^Oct$|^Nov$|^Dec$/i;
if(shouldMatch.match(regexPattern) != null) {
    // this seems happened
}
于 2013-05-10T00:27:41.683 回答
1

regexPattern是字符串,不是正则表达式。

在将其与 match 一起使用之前将其转换为 RegExp:

var regexPattern = new RegExp("^JAN$|^FEB$|^MAR$|^APR$|^MAY$|^JUN$|^JUL$|^AUG$|^SEP$|^OCT$|^NOV$|^DEC$", "gi");

此外,shouldMatch在使用之前将其转换为大写:

shouldMatch = shouldMatch.toUpperCase();
于 2013-05-10T00:28:26.233 回答
0

This should work for you.

Changed to using test

No need for the global "g" flag as you are testing the whole string from beginning "^" to end "$"

Changed string regexPattern into a RegExp object

The "i" flag is needed because you want case insensitive.

Javascript

var shouldMatch = "may";
var regexPattern = /^Jan$|^Feb$|^Mar$|^Apr$|^May$|^Jun$|^Jul$|^Aug$|^Sep$|^Oct$|^Nov$|^Dec$/i;
if(regexPattern.test(shouldMatch)) {
    alert(shouldMatch);
}

On jsfiddle

You could also make it a little shorter and a little less ugly by doing this

var regexPattern = /^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)$/i;

On jsfiddle

As an alternative to regex, you could also use String.indexOf and Array.some, and try each pattern to see if it is in the string you are testing. This example will require a modern browser or a "shim"/"polyfill" for older browsers. You could also check equality "===" if you want to match the whole string rather than see if it is contained in.

Javascript

var shouldMatch = "may";
var patterns = "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec".split("|");
var matched = patterns.some(function (pattern) {
    if (shouldMatch.toLowerCase().indexOf(pattern.toLowerCase()) !== -1) {
        alert(shouldMatch);
        return true;
    }

    return false;
});

On jsfiddle

于 2013-05-10T00:59:07.583 回答
0

或者一起运行可能性-

var Rx=/^(jan|feb|m(ar|rz)|apr|ma[iy]|jun|jul|aug|sep|o[ck]t|nov|de[cz])$/i

Rx.test('may');
于 2013-05-10T01:33:41.443 回答