0
# RandExp
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: randexp
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install randexp`
10
11
## Core Imports
12
13
```javascript
14
const RandExp = require('randexp');
15
```
16
17
Static method import:
18
19
```javascript
20
const randexp = require('randexp').randexp;
21
```
22
23
TypeScript:
24
25
```typescript
26
// CommonJS-style import (most common)
27
import * as RandExp from "randexp";
28
29
// For projects with esModuleInterop enabled
30
import RandExp from "randexp";
31
```
32
33
## Basic Usage
34
35
```javascript
36
const RandExp = require('randexp');
37
38
// Create instance and generate
39
const randexp = new RandExp(/hello+ (world|to you)/);
40
console.log(randexp.gen()); // => "hellooooooooo world"
41
42
// Static method for one-time generation
43
const result = RandExp.randexp(/[1-6]/); // => "4"
44
45
// String pattern with flags
46
const weekday = new RandExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i');
47
console.log(weekday.gen());
48
```
49
50
## Architecture
51
52
RandExp is built around several key components that work together to generate random strings:
53
54
- **Token Parser**: Uses the `ret` library to parse regular expressions into a token tree structure
55
- **Character Range System**: Manages character sets using the `drange` library for discontinuous ranges (e.g., `[a-z0-9]`)
56
- **Generation Engine**: Recursively traverses the token tree to build random strings matching the pattern
57
- **Configuration Layer**: Provides customizable random number generation, character ranges, and repetition limits
58
- **Pattern Support**: Handles complex regex features including groups, back-references, character classes, and quantifiers
59
60
## Capabilities
61
62
### RandExp Class
63
64
Main class for generating random strings from regular expressions with configurable options.
65
66
```javascript { .api }
67
/**
68
* Creates new RandExp instance from regexp or string pattern
69
* @param {RegExp|string} pattern - Regular expression or string pattern
70
* @param {string} flags - Optional flags string for string patterns
71
*/
72
class RandExp {
73
constructor(pattern, flags);
74
}
75
```
76
77
### String Generation
78
79
Generates random string matching the configured pattern.
80
81
```javascript { .api }
82
/**
83
* Generates random string matching the pattern
84
* @returns {string} Generated string
85
*/
86
gen(): string;
87
```
88
89
**Usage Example:**
90
91
```javascript
92
const randexp = new RandExp(/<([a-z]\w{0,20})>foo<\1>/);
93
console.log(randexp.gen()); // => "<m5xhdg>foo<m5xhdg>"
94
95
// Wildcard patterns
96
const wildcard = new RandExp(/random stuff: .+/);
97
console.log(wildcard.gen()); // => "random stuff: l3m;Hf9XYbI [YPaxV>U*4-_F!"
98
99
// Case insensitive
100
const caseInsensitive = new RandExp(/xxx xtreme dragon warrior xxx/i);
101
console.log(caseInsensitive.gen()); // => "xxx xtReME dRAGON warRiOR xXX"
102
```
103
104
### Static Generation Method
105
106
Convenience method for one-time string generation without instantiation.
107
108
```javascript { .api }
109
/**
110
* Static method for one-time string generation
111
* @param {RegExp|string} pattern - Regular expression or string pattern
112
* @param {string} flags - Optional flags string for string patterns
113
* @returns {string} Generated string
114
*/
115
static randexp(pattern, flags): string;
116
```
117
118
**Usage Example:**
119
120
```javascript
121
const RandExp = require('randexp');
122
123
// Direct generation
124
console.log(RandExp.randexp(/[1-6]/)); // => "4"
125
console.log(RandExp.randexp('great|good( job)?|excellent')); // => "great"
126
127
// String pattern with flags
128
console.log(RandExp.randexp('hello world', 'i'));
129
```
130
131
### Sugar Syntax
132
133
Adds `.gen()` method to RegExp prototype for syntactic convenience.
134
135
```javascript { .api }
136
/**
137
* Enables RegExp.prototype.gen() syntax
138
*/
139
static sugar(): void;
140
```
141
142
**Usage Example:**
143
144
```javascript
145
require('randexp').sugar();
146
147
console.log(/yes|no|maybe|i don't know/.gen()); // => "maybe"
148
console.log(/\d{4}-\d{2}-\d{2}/.gen()); // => "2023-05-12"
149
```
150
151
## Configuration
152
153
### Character Range Customization
154
155
Control the default character range for wildcard and character class generation.
156
157
```javascript { .api }
158
/**
159
* Default character range for generation (getter/setter)
160
* @type {DRange} Discontinuous range object (default: printable ASCII 32-126)
161
*/
162
defaultRange: DRange;
163
```
164
165
**Usage Example:**
166
167
```javascript
168
const randexp = new RandExp(/random stuff: .+/);
169
170
// Modify character range
171
randexp.defaultRange.subtract(32, 126); // Remove printable ASCII
172
randexp.defaultRange.add(0, 65535); // Add full Unicode range
173
174
console.log(randexp.gen());
175
// => "random stuff: 湐箻ໜ䫴㳸長���邓蕲뤀쑡篷皇硬剈궦佔칗븛뀃匫鴔事좍ﯣ⭼ꝏ䭍詳蒂䥂뽭"
176
177
// Global range modification
178
RandExp.prototype.defaultRange.add(48, 57); // Add digits globally
179
```
180
181
### Custom PRNG
182
183
Override the random number generation function for deterministic or cryptographic randomness.
184
185
```javascript { .api }
186
/**
187
* Random integer generation function (customizable)
188
* @param {number} a - Minimum value (inclusive)
189
* @param {number} b - Maximum value (inclusive)
190
* @returns {number} Random integer between a and b
191
*/
192
randInt(a, b): number;
193
```
194
195
**Usage Example:**
196
197
```javascript
198
const randexp = new RandExp(/\d{10}/);
199
200
// Custom PRNG (example with seedable random)
201
let seed = 12345;
202
randexp.randInt = function(a, b) {
203
seed = (seed * 9301 + 49297) % 233280;
204
return a + Math.floor((seed / 233280) * (b - a + 1));
205
};
206
207
console.log(randexp.gen()); // Deterministic output based on seed
208
```
209
210
### Infinite Repetition Limit
211
212
Control the maximum value for infinite repetition patterns like `*` and `+`.
213
214
```javascript { .api }
215
/**
216
* Maximum value for infinite repetitions (default: 100)
217
* @type {number}
218
*/
219
max: number;
220
```
221
222
**Usage Example:**
223
224
```javascript
225
const randexp = new RandExp(/no{1,}/);
226
randexp.max = 1000000; // Allow up to 1 million repetitions
227
228
// With sugar syntax
229
require('randexp').sugar();
230
const regexp = /(hi)*/;
231
regexp.max = 1000000;
232
console.log(regexp.gen());
233
```
234
235
## Instance Properties
236
237
### Pattern Flags
238
239
Read-only properties indicating pattern compilation flags.
240
241
```javascript { .api }
242
/**
243
* Case-insensitive matching flag (read-only)
244
* @type {boolean}
245
*/
246
readonly ignoreCase: boolean;
247
248
/**
249
* Multiline matching flag (read-only)
250
* @type {boolean}
251
*/
252
readonly multiline: boolean;
253
```
254
255
## Error Handling
256
257
The constructor throws an Error for invalid input types:
258
259
```javascript
260
try {
261
const invalid = new RandExp(123); // Invalid: not string or RegExp
262
} catch (error) {
263
console.log(error.message); // "Expected a regexp or string"
264
}
265
```
266
267
Invalid regex patterns are handled gracefully:
268
- Positional tokens like `/a^/` are ignored
269
- Back references to non-existing groups return empty strings
270
- Impossible character sets like `/[^\w\W]/` return empty strings
271
272
## Types
273
274
```javascript { .api }
275
/**
276
* Discontinuous range interface from the drange library
277
* Used for managing character sets and ranges
278
*/
279
interface DRange {
280
/** Add characters or ranges to the set */
281
add(from: number, to?: number): DRange;
282
/** Remove characters or ranges from the set */
283
subtract(from: number, to?: number): DRange;
284
/** Create intersection with another range */
285
intersect(other: DRange): DRange;
286
/** Create a copy of this range */
287
clone(): DRange;
288
/** Get character code at specific index */
289
index(index: number): number;
290
/** Total number of characters in this range */
291
length: number;
292
}
293
```
294
295
Import `DRange` for direct usage:
296
297
```javascript
298
const DRange = require('drange');
299
300
// Create custom range
301
const customRange = new DRange(48, 57); // Digits 0-9
302
customRange.add(65, 90); // Add uppercase A-Z
303
```
304
305
## Dependencies
306
307
- **ret**: Regular expression tokenizer and parser
308
- **drange**: Discontinuous range operations for character sets