繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM