or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-matching.mdconstruction.mdexecution.mdextensibility.mdindex.mdpattern-building.mdstring-processing.mdunicode-support.md
tile.json

tessl/npm-xregexp

Extended regular expressions with augmented syntax, named capture groups, Unicode support, and cross-browser compatibility

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/xregexp@5.1.x

To install, run

npx @tessl/cli install tessl/npm-xregexp@5.1.0

index.mddocs/

XRegExp

XRegExp provides augmented and extensible JavaScript regular expressions. You get modern syntax and flags beyond what browsers support natively, including named capture groups, Unicode property matching, free-spacing syntax with comments, and cross-browser compatibility fixes. XRegExp compiles to native RegExp objects for optimal performance while extending functionality with additional features.

Package Information

  • Package Name: xregexp
  • Package Type: npm
  • Language: JavaScript (ES6+ with TypeScript definitions)
  • Installation: npm install xregexp

Core Imports

import XRegExp from "xregexp";

For CommonJS:

const XRegExp = require("xregexp");

Basic Usage

import XRegExp from "xregexp";

// Named capture groups with free-spacing mode
const date = XRegExp(`
  (?<year>  [0-9]{4} ) -?  # year
  (?<month> [0-9]{2} ) -?  # month  
  (?<day>   [0-9]{2} )     # day
`, 'x');

// Enhanced exec with named captures
const match = XRegExp.exec('2021-02-22', date);
console.log(match.groups.year);  // '2021'

// Enhanced replace with named backreferences
const formatted = XRegExp.replace('2021-02-22', date, '$<month>/$<day>/$<year>');
console.log(formatted); // '02/22/2021'

// Unicode property matching
const identifier = XRegExp('\\p{Letter}[\\p{Letter}\\p{Number}]*', 'A');
identifier.test('變數名'); // true

Architecture

XRegExp is built around several key components:

  • Core Constructor: Enhanced RegExp constructor with extended syntax and flags
  • Static Methods: Enhanced versions of String methods (exec, match, replace, etc.) with named capture support
  • Token System: Extensible syntax system allowing custom tokens and flags via addons
  • Unicode Support: Comprehensive Unicode property, category, and script matching
  • Cross-browser Fixes: Consistent behavior across different JavaScript engines
  • Addon Architecture: Modular extensions for additional functionality

Capabilities

Regular Expression Construction

Core functionality for creating extended regular expressions with additional syntax and flags beyond native JavaScript support.

/**
 * Creates an extended regular expression object with additional syntax and flags
 * @param pattern - Regex pattern string or existing regex to copy
 * @param flags - Any combination of flags (native: dgimsuy, XRegExp: nxsA)
 * @returns Extended regular expression object
 */
function XRegExp(pattern: string | RegExp, flags?: string): RegExp;

/** XRegExp version number */
const version: string;

Regular Expression Construction

Enhanced Execution Methods

Improved regex execution methods with named capture support, position control, and cross-browser consistency.

/**
 * Enhanced exec with named capture support and position/sticky options
 * @param str - String to search
 * @param regex - Regex to search with
 * @param pos - Zero-based index to start search
 * @param sticky - Whether match must start at specified position only
 * @returns Match array with named capture properties or null
 */
function exec(str: string, regex: RegExp, pos?: number, sticky?: boolean | 'sticky'): ExecArray | null;

/**
 * Enhanced test with position/sticky support
 * @param str - String to search
 * @param regex - Regex to search with
 * @param pos - Zero-based index to start search
 * @param sticky - Whether match must start at specified position only
 * @returns Whether the regex matched
 */
function test(str: string, regex: RegExp, pos?: number, sticky?: boolean | 'sticky'): boolean;

Enhanced Execution Methods

String Processing Methods

Enhanced string methods with named backreference support and cross-browser fixes.

/**
 * Enhanced match method with scope control
 * @param str - String to search
 * @param regex - Regex to search with
 * @param scope - Use 'one' for first match or 'all' for all matches
 * @returns First match string, array of matches, or null
 */
function match(str: string, regex: RegExp, scope?: 'one' | 'all'): string | string[] | null;

/**
 * Enhanced replace with named backreference support
 * @param str - String to search
 * @param search - Search pattern to replace
 * @param replacement - Replacement string or function
 * @param scope - Use 'one' to replace first match only or 'all'
 * @returns New string with matches replaced
 */
function replace(str: string, search: RegExp | string, replacement: string | Function, scope?: 'one' | 'all'): string;

String Processing Methods

Pattern Building and Utilities

Advanced pattern construction tools including named subpatterns, template literals, and pattern combination.

/**
 * Builds regexes using named subpatterns with automatic backreference renumbering
 * @param pattern - XRegExp pattern using {{name}} for embedded subpatterns
 * @param subs - Lookup object for named subpatterns (strings or regexes)
 * @param flags - Any combination of XRegExp flags
 * @returns Regex with interpolated subpatterns
 */
function build(pattern: string, subs: Record<string, string | RegExp>, flags?: string): RegExp;

/**
 * Creates tagged template literal handler for regex construction
 * @param flags - Any combination of XRegExp flags
 * @returns Handler for template literals that construct regexes
 */
function tag(flags?: string): (literals: TemplateStringsArray, ...substitutions: any[]) => RegExp;

/**
 * Escapes regex metacharacters for literal matching
 * @param str - String to escape
 * @returns String with regex metacharacters escaped
 */
function escape(str: string): string;

Pattern Building and Utilities

Advanced Matching Features

Specialized matching capabilities including recursive/balanced delimiters and chained matching.

/**
 * Matches balanced delimiters with configurable options
 * @param str - String to search
 * @param left - Left delimiter as XRegExp pattern
 * @param right - Right delimiter as XRegExp pattern
 * @param flags - Any combination of XRegExp flags
 * @param options - Options for value names, escape chars, unbalanced handling
 * @returns Array of matches or detailed match objects
 */
function matchRecursive(str: string, left: string, right: string, flags?: string, options?: MatchRecursiveOptions): string[] | MatchRecursiveValueNameMatch[];

/**
 * Chains regexes for successive matching within previous results
 * @param str - String to search
 * @param chain - Array of regexes or objects with regex and backref properties
 * @returns Matches by the last regex in the chain
 */
function matchChain(str: string, chain: (RegExp | ChainArrayElement)[]): string[];

Advanced Matching Features

Unicode Support

Comprehensive Unicode property, category, and script matching with astral plane support.

/**
 * Adds Unicode character data for \\p{} and \\P{} tokens
 * @param data - Array of objects with Unicode character ranges
 * @param typePrefix - Optional type prefix for all provided tokens
 */
function addUnicodeData(data: UnicodeCharacterRange[], typePrefix?: string): void;

Unicode Support

Extensibility and Configuration

Tools for extending XRegExp syntax and managing optional features.

/**
 * Extends XRegExp syntax with custom tokens and flags
 * @param regex - Regex that matches the new token
 * @param handler - Function that returns replacement pattern
 * @param options - Options for scope, flags, and behavior
 */
function addToken(regex: RegExp, handler: Function, options?: TokenOptions): void;

/**
 * Installs or uninstalls optional features
 * @param options - Features to install: 'astral', 'namespacing'
 */
function install(options: string | FeatureOptions): void;
function uninstall(options: string | FeatureOptions): void;

/**
 * Checks if optional features are installed
 * @param feature - Feature name to check
 * @returns Whether the feature is installed
 */
function isInstalled(feature: 'astral' | 'namespacing'): boolean;

Extensibility and Configuration

Types

interface ExecArray extends Array<string> {
  index: number;
  input: string;
  groups?: NamedGroupsArray;
  [propName: string]: any;
}

interface NamedGroupsArray {
  [key: string]: string;
}

interface ChainArrayElement {
  regex: RegExp;
  backref: number | string;
}

interface MatchRecursiveOptions {
  escapeChar?: string;
  valueNames?: [string, string, string, string];
  unbalanced?: 'error' | 'skip' | 'skip-lazy';
}

interface MatchRecursiveValueNameMatch {
  name: string;
  value: string;
  start: number;
  end: number;
}

interface TokenOptions {
  scope?: 'default' | 'class' | 'all';
  flag?: string;
  optionalFlags?: string;
  reparse?: boolean;
  leadChar?: string;
}

interface FeatureOptions {
  astral?: boolean;
  namespacing?: boolean;
}

interface UnicodeCharacterRange {
  name: string;
  alias?: string;
  isBmpLast?: boolean;
  inverseOf?: string;
  bmp?: string;
  astral?: string;
}