簡體   English   中英

比較和索引Javascript數組中的正則表達式

[英]Compare and index regex in Javascript array

我有兩個數組:

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

您可以過濾給定的命令,如果正則表達式匹配,則將其從正則表達式數組中排除。 僅返回與正則表達式數組其余部分不匹配的命令。

 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 

我建議您將匹配正則表達式的檢查和匹配字符串的檢查分開。

從概念上講,您可能想要執行以下操作(未經測試的代碼)

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;
}
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM