ECMAScript Regular Expression Parser

3.1.0 · active · verified Tue Apr 21

`regexpp` is a specialized library for parsing and validating ECMAScript regular expressions, generating an Abstract Syntax Tree (AST) that precisely conforms to the ECMAScript specification. It provides robust tools for static analysis of regex patterns, including a parser (`RegExpParser`), a validator (`RegExpValidator`), and a visitor pattern (`RegExpVisitor`) for AST traversal. The current stable version, 3.2.0, actively receives updates to support the latest ECMAScript features and Unicode versions. This package differentiates itself by offering fine-grained control over the parsing process, allowing specification of ECMAScript version targets and Unicode flags, making it invaluable for linters, code transformers, and tools that require a deep, standards-compliant understanding and manipulation of regular expressions. Its release cadence is active, with significant updates roughly yearly for major versions and minor releases as needed to keep pace with spec changes and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing a regular expression literal, validating it, and then traversing its Abstract Syntax Tree (AST) using the visitor pattern.

import { parseRegExpLiteral, visitRegExpAST, RegExpValidator } from 'regexpp';

const regexSource = '/^(hello|world)\s+\d{4}$/ui';

try {
  // Parse the regular expression literal
  const ast = parseRegExpLiteral(regexSource, { ecmaVersion: 2021 });
  console.log('Successfully parsed regex:', regexSource);
  console.log('Pattern body:', ast.pattern.raw);
  console.log('Flags:', ast.flags.raw);

  // Validate the regular expression
  const validator = new RegExpValidator({ ecmaVersion: 2021 });
  validator.validateLiteral(regexSource);
  console.log('Successfully validated regex:', regexSource);

  // Visit the AST nodes
  console.log('\nTraversing AST:');
  visitRegExpAST(ast, {
    onPatternEnter(node) { console.log(`  Entering Pattern: ${node.raw}`); },
    onGroupEnter(node) { console.log(`  Entering Group: ${node.raw}`); },
    onCharacterEnter(node) { console.log(`  Entering Character: ${node.raw}`); },
    onQuantifierEnter(node) { console.log(`  Entering Quantifier: ${node.raw}`); }
  });

} catch (error) {
  console.error('Error processing regex:', error.message);
}

view raw JSON →