Generating strings from regular expression in JavaScript
11,412
Solution 1
If you're using JavaScript, there's Randexp which generates random strings that match a given regex.
Solution 2
Use randexp.js, it does exactly what you want:
console.log(new RandExp(/^([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}$/).gen());
console.log(new RandExp(/^[0-9]{4}$/).gen());
console.log(new RandExp(/^[0-9,A-Z]{4}$/).gen());
console.log(new RandExp(/^([A-Z]){5}([0-9]){4}([A-Z]){1}$/).gen());
<script src="https://github.com/fent/randexp.js/releases/download/v0.4.3/randexp.min.js"></script>
Related videos on Youtube
Author by
rahulroy9202
Updated on June 26, 2022Comments
-
rahulroy9202 almost 2 years
I think it can be done by generating strings using brute force and then try to match them to the supplied regex and printing if match.
But is there a better way to do this?
Regex are used to test if a string matches a pattern. I am aware of that. I thought it would be interesting to do it the way around.
-
Sjoerd about 7 yearsPossible duplicate of Generate a random string based on a regular expression
-
Dave NewtonHigher Order Perl has a section discussing this problem. It's worth reading for other reasons, too.
-
Sikshya MaharjanWhat's the problem you're trying to solve, what's the question?
-
-
Anderson Green about 4 yearsRandexp generates only one random string from a regex. To generate every possible match, you can use genexp.js instead.