Create random strings that match a given regular expression.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
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.
npm install randexpconst 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";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());RandExp is built around several key components that work together to generate random strings:
ret library to parse regular expressions into a token tree structuredrange library for discontinuous ranges (e.g., [a-z0-9])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);
}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"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'));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"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 globallyOverride 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 seedControl 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());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;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:
/a^/ are ignored/[^\w\W]/ return empty strings/**
* 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