[英]JavaScript RegExp to match strings using wildcards * and?
我有一個名單列表,我需要一個功能供用戶使用通配符*和?來過濾它們。 (任何字符串和任何字符。)我知道我需要清理用戶輸入以避免語法注入(有意或無意),但我不知道需要清理多少。
我需要更換*和? 從用戶輸入?
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 */
謝謝。
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(""));
}
嗯,我真的認為你不需要在這里打掃任何東西。 如果用戶沒有輸入有效的正則表達式,則new RegExp(userInput)
將失敗,它將永遠不會eval()
字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.