功能说明
globToRegExp 把常见 Glob 语法编译为锚定正则,matchGlob 用编译结果匹配路径。支持单星号匹配段内任意字符、双星号跨目录、问号匹配单个非斜杠字符、方括号字符组与花括号多选。适合忽略文件规则、构建工具文件筛选、静态资源分类和命令行批量操作。编译与匹配分离,批量处理时可复用正则。
关键代码
反斜杠统一转换为正斜杠,便于跨平台。单星号生成不跨斜杠的字符类,双星号后跟斜杠时生成可选的任意目录前缀,单独的星号匹配任意字符。问号转换为非斜杠单字符。方括号内以感叹号开头转换为正则否定字符组,花括号内容按逗号拆分并逐个转义后组成非捕获分组。其余字符均经过转义,最后添加首尾锚点。
使用注意
字符组内部的范围与转义直接交给正则,恶意或异常模式可能产生意外结果,来自用户的模式应限制长度并捕获编译异常。双星号语义只覆盖常见形式,不支持 extglob 的复杂组合。以点开头的文件不会被特殊排除,需要时应把规则写进模式。该匹配器针对相对路径,匹配前应统一分隔符并去掉开头的 ./。
验证方式
测试 .ts 不匹配子目录、**/.ts 匹配多层目录、src/**/test 可选中间目录、? 与字符组、{js,ts} 多选和大小写敏感选项。测试未闭合方括号或花括号会抛错,空模式与非字符串输入被拒绝。再用转义字符构造包含点号与加号的文件名,确认这些字符按字面匹配而不是正则元字符。
代码示例
export interface GlobOptions {
caseInsensitive?: boolean;
}
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^$()|[\]{}\\]/g, "\\$&");
}
export function globToRegExp(pattern: string, options: GlobOptions = {}): RegExp {
if (typeof pattern !== "string" || pattern.length === 0) {
throw new TypeError("pattern must be a non-empty string");
}
const normalized = pattern.replace(/\\/g, "/");
let source = "";
for (let index = 0; index < normalized.length; index += 1) {
const char = normalized[index]!;
if (char === "*") {
if (normalized[index + 1] === "*") {
if (normalized[index + 2] === "/") {
source += "(?:.*/)?";
index += 2;
} else {
source += ".*";
index += 1;
}
} else {
source += "[^/]*";
}
} else if (char === "?") {
source += "[^/]";
} else if (char === "[") {
const end = normalized.indexOf("]", index + 1);
if (end === -1) throw new SyntaxError("unterminated character class");
const body = normalized.slice(index + 1, end);
source += "[" + (body.startsWith("!") ? "^" + body.slice(1) : body) + "]";
index = end;
} else if (char === "{") {
const end = normalized.indexOf("}", index + 1);
if (end === -1) throw new SyntaxError("unterminated brace group");
const alternatives = normalized.slice(index + 1, end).split(",").map(escapeRegExp);
source += "(?:" + alternatives.join("|") + ")";
index = end;
} else {
source += escapeRegExp(char);
}
}
return new RegExp("^" + source + "$", options.caseInsensitive ? "i" : "");
}
export function matchGlob(path: string, pattern: string, options: GlobOptions = {}): boolean {
return globToRegExp(pattern, options).test(String(path).replace(/\\/g, "/"));
}