Generate strings that match a Regular Expression pattern. Efficiently generate all possible matches, or only the quantity you need.
Have you ever:
- scrutinized a Regular Expression while trying to visualize what it does and doesn't match?
- crafted a list of strings to test whether a Regular Expression is working as intended?
- needed to generate filler data like phone numbers, addresses, zip codes, and email addresses?
regex-to-strings
helps with problems like these!
The regExPattern
parameter supports three formats:
- A
RegExp
object, like/[a-z]/i
- A
string
that looks like aRegExp
object, like"/[a-z]/i"
- A
string
containing just a Regular Expression pattern, like"[a-z]"
The returned object contains two properties:
count
: The total number of strings that matchregExPattern
getIterator()
: A generator that yields strings matched byregExPattern
import { expand } from 'regex-to-strings';
const phoneNumberPattern = /((\(555\) ?)|(555-))?\d{3}-\d{4}/;
const phoneNumberExpander = expand(phoneNumberPattern);
console.log(phoneNumberExpander.count); // 40000000
for (const phoneNumber of phoneNumberExpander.getIterator()) {
console.log(phoneNumber);
// (555)547-4836
// 476-2063
// 467-2475
// (555) 194-2532
// (555)403-4986
// 555-838-9771
// etc.
}
A shortcut to the count
property of expand(regExPattern)
.
import { count } from 'regex-to-strings';
const numStrings = count(/[a-z]{5}/i);
console.log(numStrings); // 380204032
A shortcut to take n
strings from expand(regExPattern).getIterator()
.
import { expandN } from 'regex-to-strings';
const strings = expandN(/\d{3,5}/, 5);
console.log(strings); // ['84504', '94481', '3971', '69398', '7792']
If the Regular Expression matches fewer than n
strings, the returned array will contain fewer than n
elements.
import { expandN } from 'regex-to-strings';
const strings = expandN(/[abc]/, 100);
console.log(strings); // ['b', 'a', 'c']
A shortcut to get all strings from expand(regExPattern).getIterator()
.
import { expandAll } from 'regex-to-strings';
const strings = expandAll(/\d/);
console.log(strings); // ['6', '5', '0', '2', '7', '9', '4', '3', '1', '8']