使用通配符*和?匹配字符串的JavaScript RegExp

问题描述:

我有一个名称列表,我需要一个功能供用户使用通配符*和?进行过滤。 (任何字符串和任何字符)。我知道我需要清理用户输入以避免语法注入(有意或无意),但我不知道需要清理多少。使用通配符*和?匹配字符串的JavaScript RegExp

对于我需要替换*和?来自用户输入?

var names = [...]; 
var userInput = field.value; 

/* Replace * and ? for their equivalent in regexp */ 
userInput = userInput.replaceAll(...); 
userInput = userInput.replaceAll(...); 

/* clean the input */ 
userInput = userInput.replaceAll(...); 
userInput = userInput.replaceAll(...); 
... 

var regex = new Regexp(userInput); 

var matches = []; 
for (name in names) { 
    if (regex.test(name)) { 
     matches.push(name); 
    } 
} 

/* Show the results */ 

谢谢。

恩,我真的不认为你需要在这里清理任何东西。如果用户没有输入有效的正则表达式,new RegExp(userInput)将会失败,它将永远不会是eval()的字符串。

function globToRegex (glob) { 
    var specialChars = "\\^$*+?.()|{}[]"; 
    var regexChars = ["^"]; 
    for (var i = 0; i < glob.length; ++i) { 
     var c = glob.charAt(i); 
     switch (c) { 
      case '?': 
       regexChars.push("."); 
       break; 
      case '*': 
       regexChars.push(".*"); 
       break; 
      default: 
       if (specialChars.indexOf(c) >= 0) { 
        regexChars.push("\\"); 
       } 
       regexChars.push(c); 
     } 
    } 
    regexChars.push("$"); 
    return new RegExp(regexChars.join("")); 
} 
+0

在根正则表达式中添加^ $。 – 2011-04-09 01:54:33

+0

感谢您发布此方法。我只是将它扩展为可选的不区分大小写,所以我最后两行是: if(insensitive){modifiers ='i'};返回新的RegExp(regexChars.join(“”),modifiers); – Lee 2012-07-06 16:43:57