如何在 javascript 裡實作出支援星號(wildcard) 的字串比對,例如 chrome extension 的 matches url,
chrome extension – Match patterns
https://developer.chrome.com/docs/extensions/develop/concepts/match-patterns
答案:
https://stackoverflow.com/questions/26246601/wildcard-string-comparison-in-javascript
I think you meant something like “*” (star) as a wildcard for example:
- “a*b” => everything that starts with “a” and ends with “b”
- “a*” => everything that starts with “a”
- “*b” => everything that ends with “b”
- “*a*” => everything that has an “a” in it
- “*a*b*”=> everything that has an “a” in it, followed by anything, followed by a “b”, followed by anything
or in your example: “bird*” => everything that starts with bird
I had a similar problem and wrote a function with RegExp:
//Short code
function matchRuleShort(str, rule) {
var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\\");
return new RegExp("^" + rule.split("*").map(escapeRegex).join(".*") + "$").test(str);
}
//Explanation code
function matchRuleExpl(str, rule) {
// for this solution to work on any string, no matter what characters it has
var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\\");
// "." => Find a single character, except newline or line terminator
// ".*" => Matches any string that contains zero or more characters
rule = rule.split("*").map(escapeRegex).join(".*");
// "^" => Matches any string with the following at the beginning of it
// "$" => Matches any string with that in front at the end of it
rule = "^" + rule + "$"
//Create a regular expression object for matching string
var regex = new RegExp(rule);
//Returns true if it finds a match, otherwise it returns false
return regex.test(str);
}
//Examples
alert(
"1. " + matchRuleShort("bird123", "bird*") + "\n" +
"2. " + matchRuleShort("123bird", "*bird") + "\n" +
"3. " + matchRuleShort("123bird123", "*bird*") + "\n" +
"4. " + matchRuleShort("bird123bird", "bird*bird") + "\n" +
"5. " + matchRuleShort("123bird123bird123", "*bird*bird*") + "\n" +
"6. " + matchRuleShort("s[pe]c 3 re$ex 6 cha^rs", "s[pe]c*re$ex*cha^rs") + "\n" +
"7. " + matchRuleShort("should not match", "should noo*oot match") + "\n"
);
或範例2號:
function wildcardMatchRegExp(text, pattern) {
const regexPattern = new RegExp(
"^" +
pattern
.replace(/\?/g, ".")
.replace(/\*/g, ".*") +
"$"
);
return regexPattern.test(text);
}
if (wildcardMatchRegExp(text, pattern)) {
console.log("Pattern is Matched");
}