在Javascript数组中比较和索引正则表达式

时间:2017-02-16 15:03:46

标签: javascript arrays regex

我有两个数组:

enteredCommands = ["valid", "this", 1.1];
validParameters = [/valid/, /alsoValid/, /this|that/, /\d+(\.)?\d*/];

我想循环浏览所有enteredCommands,如果它存在于validParameters中,请将其从validParameters中删除,如果它没有,则中断。

如果我将validParameters更改为:

,我不知道如何以这种方式比较正则表达式

validParameters = ["valid", "alsoValid", /this|that/, /\d+(\.)?\d*/];

并使用:

var ok2go = true;
// For each entered command...
for (var i = 0; i < commands.length; i++) {
     // Check to see that it is a valid parameter
     if (validParameters.indexOf(commands[i]) === -1) {
         // If not, an invalid command was entered.
         ok2go = false;
         break;
     // If valid, remove from list of valid parameters so as to prevent duplicates.
     } else {
         validParameters.splice(validParameters.indexOf(commands[i]), 1);
     }
     return ok2go;
}

if (ok2go) {
   // do stuff if all the commands are valid
} else {
   alert("Invalid command");
}

它按照我想要的方式用于字符串,但显然不适用于那些需要正则表达式的值。有什么方法可以解决这个问题吗?

测试用例:

enteredCommands = ["valid", "this", 1.1, 3];
// Expected Result: ok2go = false because 2 digits were entered

enteredCommands = ["valid", "alsoValid", "x"];
// Expected Result: ok2go = false because x was entered

enteredCommands = ["valid", "alsoValid", 1];
// Expected Result: ok2go = true because no invalid commands were found so we can continue on with the rest of the code

2 个答案:

答案 0 :(得分:2)

您可以过滤给定的命令,如果正则表达式匹配,则将其从正则表达式数组中排除。仅返回与正则表达式数组的其余部分不匹配的逗号。

&#13;
&#13;
function check(array) {
    var regex = [/valid/, /alsoValid/, /this|that/, /\d+(\.)?\d*/];

    return array.filter(function (a) {
        var invalid = true;
        regex = regex.filter(function (r) {
            if (!r.test(a)) {
                return true;
            }
            invalid = false;					
        });
        invalid && alert('invalid command: ' + a);
        return invalid;
    });
}

console.log(check(["valid", "this", 1.1, 3]));   // 2 digits were entered
console.log(check(["valid", "alsoValid", "x"])); // x was entered
console.log(check(["valid", "alsoValid", 1]));   // nothing, no invalid commands were found
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我建议您拆分检查匹配的正则表达式并检查匹配的字符串。

从概念上讲,您可能希望执行以下操作(代码未经过测试)

var validStringParameters = ["valid", "alsoValid"];
var validRegexMatches = [/valid/, /alsoValid/, /this|that/, /\d+(\.)?\d*/];

var validCommands = enteredcommands.filter(function(command){
if (validStringParameters.indexOf(command) !== -1){
return true;
}
for (var i = 0; i < validRegexMatches.length; i++){
if (command.test(validRegexMatches[i]){
return true;
})
return false;
}
})