CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-randexp

Create random strings that match a given regular expression.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

RandExp

RandExp generates random strings that match given regular expressions. It supports complex regex patterns including grouping, piping, character sets, ranges, back references, wildcards, and case-insensitive matching.

Package Information

  • Package Name: randexp
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install randexp

Core Imports

const RandExp = require('randexp');

Static method import:

const randexp = require('randexp').randexp;

TypeScript:

// CommonJS-style import (most common)
import * as RandExp from "randexp";

// For projects with esModuleInterop enabled
import RandExp from "randexp";

Basic Usage

const RandExp = require('randexp');

// Create instance and generate
const randexp = new RandExp(/hello+ (world|to you)/);
console.log(randexp.gen()); // => "hellooooooooo world"

// Static method for one-time generation
const result = RandExp.randexp(/[1-6]/); // => "4"

// String pattern with flags
const weekday = new RandExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i');
console.log(weekday.gen());

Architecture

RandExp is built around several key components that work together to generate random strings:

  • Token Parser: Uses the ret library to parse regular expressions into a token tree structure
  • Character Range System: Manages character sets using the drange library for discontinuous ranges (e.g., [a-z0-9])
  • Generation Engine: Recursively traverses the token tree to build random strings matching the pattern
  • Configuration Layer: Provides customizable random number generation, character ranges, and repetition limits
  • Pattern Support: Handles complex regex features including groups, back-references, character classes, and quantifiers

Capabilities

RandExp Class

Main class for generating random strings from regular expressions with configurable options.

/**
 * Creates new RandExp instance from regexp or string pattern
 * @param {RegExp|string} pattern - Regular expression or string pattern
 * @param {string} flags - Optional flags string for string patterns
 */
class RandExp {
  constructor(pattern, flags);
}

String Generation

Generates random string matching the configured pattern.

/**
 * Generates random string matching the pattern
 * @returns {string} Generated string
 */
gen(): string;

Usage Example:

const randexp = new RandExp(/<([a-z]\w{0,20})>foo<\1>/);
console.log(randexp.gen()); // => "<m5xhdg>foo<m5xhdg>"

// Wildcard patterns
const wildcard = new RandExp(/random stuff: .+/);
console.log(wildcard.gen()); // => "random stuff: l3m;Hf9XYbI [YPaxV>U*4-_F!"

// Case insensitive
const caseInsensitive = new RandExp(/xxx xtreme dragon warrior xxx/i);
console.log(caseInsensitive.gen()); // => "xxx xtReME dRAGON warRiOR xXX"

Static Generation Method

Convenience method for one-time string generation without instantiation.

/**
 * Static method for one-time string generation
 * @param {RegExp|string} pattern - Regular expression or string pattern
 * @param {string} flags - Optional flags string for string patterns
 * @returns {string} Generated string
 */
static randexp(pattern, flags): string;

Usage Example:

const RandExp = require('randexp');

// Direct generation
console.log(RandExp.randexp(/[1-6]/)); // => "4"
console.log(RandExp.randexp('great|good( job)?|excellent')); // => "great"

// String pattern with flags
console.log(RandExp.randexp('hello world', 'i'));

Sugar Syntax

Adds .gen() method to RegExp prototype for syntactic convenience.

/**
 * Enables RegExp.prototype.gen() syntax
 */
static sugar(): void;

Usage Example:

require('randexp').sugar();

console.log(/yes|no|maybe|i don't know/.gen()); // => "maybe"
console.log(/\d{4}-\d{2}-\d{2}/.gen()); // => "2023-05-12"

Configuration

Character Range Customization

Control the default character range for wildcard and character class generation.

/**
 * Default character range for generation (getter/setter)
 * @type {DRange} Discontinuous range object (default: printable ASCII 32-126)
 */
defaultRange: DRange;

Usage Example:

const randexp = new RandExp(/random stuff: .+/);

// Modify character range
randexp.defaultRange.subtract(32, 126);  // Remove printable ASCII
randexp.defaultRange.add(0, 65535);      // Add full Unicode range

console.log(randexp.gen());
// => "random stuff: 湐箻ໜ䫴␩⶛㳸長���邓蕲뤀쑡篷皇硬剈궦佔칗븛뀃匫鴔事좍ﯣ⭼ꝏ䭍詳蒂䥂뽭"

// Global range modification
RandExp.prototype.defaultRange.add(48, 57); // Add digits globally

Custom PRNG

Override the random number generation function for deterministic or cryptographic randomness.

/**
 * Random integer generation function (customizable)
 * @param {number} a - Minimum value (inclusive)
 * @param {number} b - Maximum value (inclusive)
 * @returns {number} Random integer between a and b
 */
randInt(a, b): number;

Usage Example:

const randexp = new RandExp(/\d{10}/);

// Custom PRNG (example with seedable random)
let seed = 12345;
randexp.randInt = function(a, b) {
  seed = (seed * 9301 + 49297) % 233280;
  return a + Math.floor((seed / 233280) * (b - a + 1));
};

console.log(randexp.gen()); // Deterministic output based on seed

Infinite Repetition Limit

Control the maximum value for infinite repetition patterns like * and +.

/**
 * Maximum value for infinite repetitions (default: 100)
 * @type {number}
 */
max: number;

Usage Example:

const randexp = new RandExp(/no{1,}/);
randexp.max = 1000000; // Allow up to 1 million repetitions

// With sugar syntax
require('randexp').sugar();
const regexp = /(hi)*/;
regexp.max = 1000000;
console.log(regexp.gen());

Instance Properties

Pattern Flags

Read-only properties indicating pattern compilation flags.

/**
 * Case-insensitive matching flag (read-only)
 * @type {boolean}
 */
readonly ignoreCase: boolean;

/**
 * Multiline matching flag (read-only)
 * @type {boolean}
 */
readonly multiline: boolean;

Error Handling

The constructor throws an Error for invalid input types:

try {
  const invalid = new RandExp(123); // Invalid: not string or RegExp
} catch (error) {
  console.log(error.message); // "Expected a regexp or string"
}

Invalid regex patterns are handled gracefully:

  • Positional tokens like /a^/ are ignored
  • Back references to non-existing groups return empty strings
  • Impossible character sets like /[^\w\W]/ return empty strings

Types

/**
 * Discontinuous range interface from the drange library
 * Used for managing character sets and ranges
 */
interface DRange {
  /** Add characters or ranges to the set */
  add(from: number, to?: number): DRange;
  /** Remove characters or ranges from the set */
  subtract(from: number, to?: number): DRange;
  /** Create intersection with another range */
  intersect(other: DRange): DRange;
  /** Create a copy of this range */
  clone(): DRange;
  /** Get character code at specific index */
  index(index: number): number;
  /** Total number of characters in this range */
  length: number;
}

Import DRange for direct usage:

const DRange = require('drange');

// Create custom range
const customRange = new DRange(48, 57); // Digits 0-9
customRange.add(65, 90); // Add uppercase A-Z

Dependencies

  • ret: Regular expression tokenizer and parser
  • drange: Discontinuous range operations for character sets

Install with Tessl CLI

npx tessl i tessl/npm-randexp
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/randexp@0.5.x
Publish Source
CLI
Badge
tessl/npm-randexp badge