RegExp Literal AST Parser

1.1.40 · active · verified Tue Apr 21

regexp-parser-literal is a JavaScript and TypeScript library designed for parsing regular expression literals into an Abstract Syntax Tree (AST). It provides a convenient API built on top of the `regexpp2` library, offering functions such as `parseRegExp` to convert a full regular expression string into its AST representation, `parseFlags` for flag extraction, `parsePattern` for the pattern part, and `astToString` for serializing an AST back into a regular expression string. The current stable version is 1.1.40. While it does not adhere to a strict release cadence, updates are typically driven by enhancements to its underlying `regexpp2` dependency or specific utility requirements, such as improved emoji handling. A key differentiator is its ready-to-use utility functions that streamline common regex AST manipulations and its inclusion of a pre-defined `EMOJI_REGEX`. This makes it particularly useful for applications requiring programmatic analysis, validation, transformation, or generation of regular expressions, often found in linters, code formatting tools, or domain-specific language compilers. It aims to simplify direct interaction with the powerful `regexpp2` parser for common use cases.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing a full regex literal, a pattern, converting an AST back to a string, and utilizing the `EMOJI_REGEX`.

import { parseRegExp, astToString, EMOJI_REGEX } from 'regexp-parser-literal';
import { defaultRegExpParser } from 'regexp-parser-literal';

// Example 1: Parsing a complete regular expression literal
const regexInput = "/hello world!/gi";
const astLiteral = parseRegExp(regexInput);
console.log('Parsed AST Type:', astLiteral.type); // RegExpLiteral
console.log('Parsed AST Body Type:', astLiteral.body.type); // Pattern
console.log('Parsed AST Flags Type:', astLiteral.flags.type); // Flags
console.log('Extracted Flags:', astLiteral.flags.raw);

// Example 2: Parsing only a pattern string using the default parser instance
const patternInput = "foo|bar\\d+";
const patternAst = defaultRegExpParser.parsePattern(patternInput);
console.log('Parsed Pattern AST Type:', patternAst.type); // Pattern
console.log('Number of pattern elements:', patternAst.elements.length);

// Example 3: Converting an AST back to a string
// In a real scenario, you would modify the AST elements before stringification
const stringifiedRegex = astToString(astLiteral);
console.log('Stringified AST back to regex:', stringifiedRegex);

// Example 4: Using the provided EMOJI_REGEX
const textWithEmoji = "Hello 👋 world! 🌍";
console.log('Does text contain emoji?', EMOJI_REGEX.test(textWithEmoji));
console.log('Matching emojis:', textWithEmoji.match(EMOJI_REGEX)?.join(', '));

view raw JSON →