CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-regexpp

Regular expression parser for ECMAScript that generates Abstract Syntax Trees from regex patterns.

Pending
Overview
Eval results
Files

core-functions.mddocs/

Core Functions

The three main convenience functions provide simple access to RegexPP's most common regex processing operations without requiring class instantiation.

Capabilities

Parse RegExp Literal

Parses a regular expression literal string or RegExp object into an Abstract Syntax Tree.

/**
 * Parse a given regular expression literal then make AST object.
 * This is equivalent to `new RegExpParser(options).parseLiteral(String(source))`
 * @param source - The source code to parse (string like "/abc/gi" or RegExp object)
 * @param options - The parsing options
 * @returns The AST of the regular expression
 */
function parseRegExpLiteral(
  source: string | RegExp,
  options?: RegExpParser.Options,
): AST.RegExpLiteral;

Usage Examples:

import { parseRegExpLiteral } from "regexpp";

// Parse from string literal
const ast1 = parseRegExpLiteral("/[a-z]+/gi");
console.log(ast1.pattern.alternatives[0].elements.length); // Number of elements

// Parse from RegExp object  
const ast2 = parseRegExpLiteral(new RegExp("[0-9]+", "g"));
console.log(ast2.flags.global); // true

// Parse with options
const ast3 = parseRegExpLiteral("/(?<=\\w)\\d+/", {
  ecmaVersion: 2018,  // Enable lookbehind assertions
  strict: false
});

Validate RegExp Literal

Validates the syntax of a regular expression literal string without generating an AST.

/**
 * Validate a given regular expression literal.
 * This is equivalent to `new RegExpValidator(options).validateLiteral(source)`
 * @param source - The source code to validate (string like "/abc/gi")
 * @param options - The validation options
 * @throws {RegExpSyntaxError} If the regex has invalid syntax
 */
function validateRegExpLiteral(
  source: string,
  options?: RegExpValidator.Options,
): void;

Usage Examples:

import { validateRegExpLiteral } from "regexpp";

// Basic validation
try {
  validateRegExpLiteral("/[a-z]+/gi");
  console.log("Valid regex");
} catch (error) {
  console.log("Invalid regex:", error.message);
}

// Validation with specific ECMAScript version
try {
  validateRegExpLiteral("/(?<=\\w)\\d+/", {
    ecmaVersion: 2017  // This will throw - lookbehind requires ES2018
  });
} catch (error) {
  console.log("Feature not supported in ES2017");
}

// Strict mode validation (disables Annex B features)
try {
  validateRegExpLiteral("/\\8/", {
    strict: true  // This will throw - \\8 is Annex B syntax
  });
} catch (error) {
  console.log("Annex B syntax not allowed in strict mode");
}

Visit RegExp AST

Traverses an Abstract Syntax Tree using the visitor pattern with custom callbacks.

/**
 * Visit each node of a given AST.
 * This is equivalent to `new RegExpVisitor(handlers).visit(node)`
 * @param node - The AST node to visit (typically the root RegExpLiteral)
 * @param handlers - The visitor callbacks for different node types
 */
function visitRegExpAST(
  node: AST.Node,
  handlers: RegExpVisitor.Handlers,
): void;

Usage Examples:

import { parseRegExpLiteral, visitRegExpAST } from "regexpp";

const ast = parseRegExpLiteral("/[a-z]+(\\d{2,4})?/gi");

// Count different node types
let counts = { characters: 0, quantifiers: 0, groups: 0 };

visitRegExpAST(ast, {
  onCharacterEnter(node) {
    counts.characters++;
  },
  onQuantifierEnter(node) {
    counts.quantifiers++;
    console.log(`Found quantifier: ${node.raw} (min: ${node.min}, max: ${node.max})`);
  },
  onCapturingGroupEnter(node) {
    counts.groups++;
    console.log(`Found capturing group: ${node.name || 'unnamed'}`);
  }
});

console.log(counts); // { characters: X, quantifiers: Y, groups: Z }

// Extract all character classes
const characterClasses: string[] = [];
visitRegExpAST(ast, {
  onCharacterClassEnter(node) {
    characterClasses.push(node.raw);
  }
});
console.log(characterClasses); // ["[a-z]"]

Types

// Options interfaces used by core functions
interface RegExpParser.Options {
  /** The flag to disable Annex B syntax. Default is false */
  strict?: boolean;
  /** ECMAScript version. Default is 2022 */
  ecmaVersion?: EcmaVersion;
}

interface RegExpValidator.Options {
  /** The flag to disable Annex B syntax. Default is false */
  strict?: boolean;
  /** ECMAScript version. Default is 2022 */
  ecmaVersion?: EcmaVersion;
  // Plus many optional validation callback functions
}

interface RegExpVisitor.Handlers {
  // Optional callback functions for each AST node type
  onRegExpLiteralEnter?(node: AST.RegExpLiteral): void;
  onRegExpLiteralLeave?(node: AST.RegExpLiteral): void;
  onPatternEnter?(node: AST.Pattern): void;
  onPatternLeave?(node: AST.Pattern): void;
  // ... many more callback options for all node types
}

type EcmaVersion = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022;

Install with Tessl CLI

npx tessl i tessl/npm-regexpp

docs

ast-types.md

core-functions.md

index.md

parsing.md

validation.md

visitor.md

tile.json