Glob Pattern Matcher

Compile glob patterns with star, globstar, question marks, character classes and braces into anchored regular expressions.

TypescriptCli Tooling

Code

snippet
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, "/"));
}