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.

Releases for browser

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>
Share:
11,412

Related videos on Youtube

rahulroy9202
Author by

rahulroy9202

Updated on June 26, 2022

Comments

  • rahulroy9202
    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.

  • Anderson Green
    Anderson Green about 4 years
    Randexp generates only one random string from a regex. To generate every possible match, you can use genexp.js instead.

Related