RegExp Tree: Regular Expression Processor

0.1.27 · active · verified Sun Apr 19

regexp-tree is a JavaScript library designed for comprehensive processing of regular expressions. It provides a full suite of APIs including a parser that generates an Abstract Syntax Tree (AST) based on the ECMAScript regular expression grammar, tools for AST traversal and transformation, an optimizer, and an interpreter. It also features a compatibility transpiler and supports custom regular expression extensions. Currently stable at version 0.1.27, it appears to be actively maintained, though release cadence isn't explicitly stated. Its key differentiators include its extensive set of processing capabilities beyond simple parsing, offering deep inspection, modification, and optimization of regular expressions. The library also ships with TypeScript type definitions, enhancing developer experience for TypeScript users.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing a regular expression into an Abstract Syntax Tree (AST), then applying a custom transformation to modify a character, and finally optimizing the regex for improved performance or conciseness.

import * as regexpTree from 'regexp-tree';

// Example: Parse, transform, and optimize a regular expression
const regexString = '/a[bc]d|efg+/gi';

try {
  // 1. Parse the regular expression to get its AST
  const ast = regexpTree.parse(regexString);
  console.log('Original AST (partial):', JSON.stringify(ast, null, 2).substring(0, 100) + '...');

  // 2. Transform the AST (e.g., replace a character)
  const transformedAst = regexpTree.transform(regexString, {
    char(path) {
      if (path.node.value === 'b') {
        path.node.value = 'x'; // Change 'b' to 'x'
      }
    }
  });
  console.log('Transformed Regexp:', transformedAst.toString()); // Outputs transformed regex string

  // 3. Optimize the regular expression
  const optimizedAst = regexpTree.optimize(regexString);
  console.log('Optimized Regexp:', optimizedAst.toString());

} catch (error) {
  if (error instanceof Error) {
    console.error('Error processing regex:', error.message);
  } else {
    console.error('An unknown error occurred:', error);
  }
}

view raw JSON →