Glob Pattern Matcher

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

TypescriptCli Tooling

Code

typescriptsnippet
52 lines
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, "/"));
}

How it works

Glob Pattern Matcher is built around the functions escapeRegExp, globToRegExp and matchGlob.

Iteration happens inside for (let index = 0; index < normalized.length; index += 1) — everything outside it runs once. When the guard condition holds, TypeError and SyntaxError is thrown rather than a bogus value returned.

The result is a fresh construction, so callers can keep their originals.

Points of care

  • The guard typeof pattern !== "string" || pattern.length === 0 short-circuits the flow with an early throw when its condition holds.

Using it

The entry-point signature is export function globToRegExp(pattern: string, options: GlobOptions = {})

The surface worth importing is globToRegExp; the helpers around it are private to the snippet.

Key statements

return globToRegExp(pattern, options).test(String(path).replace(/\\/g, "/"));
source += "[" + (body.startsWith("!") ? "^" + body.slice(1) : body) + "]";
return new RegExp("^" + source + "$", options.caseInsensitive ? "i" : "");

Interactive Tools for This Topic

FAQ

Does `globToRegExp` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
Is there a failure path for bad input?
The code throws `TypeError` and `SyntaxError` — the guard `typeof pattern !== "string" || pattern.length === 0` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. The file defines `escapeRegExp`, `globToRegExp`, `matchGlob` at load time.