js实现通配符
实现通配符匹配的方法
在JavaScript中实现通配符匹配可以通过正则表达式或自定义函数来完成。以下是几种常见的实现方式:
使用正则表达式转换
将通配符模式转换为正则表达式,例如将*转换为.*,将?转换为.,然后进行匹配。
function wildcardToRegex(pattern) {
const escapedPattern = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&');
const regexPattern = escapedPattern.replace(/\*/g,.*').replace(/\?/g, '.');
return new RegExp(`^${regexPattern}$`);
}
const regex = wildcardToRegex('file*.txt');
console.log(regex.test('file123.txt')); // true
自定义通配符匹配函数
通过逐字符比较实现通配符匹配逻辑,支持*和?。
function isMatch(str, pattern) {
let strIndex = 0, patternIndex = 0;
let starIndex = -1, strTempIndex = -1;
while (strIndex < str.length) {
if (patternIndex < pattern.length &&
(pattern[patternIndex] === '?' || str[strIndex] === pattern[patternIndex])) {
strIndex++;
patternIndex++;
} else if (patternIndex < pattern.length && pattern[patternIndex] === '*') {
starIndex = patternIndex;
strTempIndex = strIndex;
patternIndex++;
} else if (starIndex !== -1) {
patternIndex = starIndex + 1;
strIndex = strTempIndex + 1;
strTempIndex++;
} else {
return false;
}
}
while (patternIndex < pattern.length && pattern[patternIndex] === '*') {
patternIndex++;
}
return patternIndex === pattern.length;
}
console.log(isMatch('test.txt', '*.txt')); // true
使用第三方库
某些库如minimatch提供了成熟的通配符匹配功能。

const minimatch = require('minimatch');
console.log(minimatch('file123.txt', 'file*.txt')); // true
注意事项
- 正则表达式方式需注意特殊字符的转义。
- 自定义函数需处理边界条件,如空字符串或空模式。
- 第三方库可能提供更丰富的功能,但会增加依赖。






