15

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.

12
  • 1
    Higher Order Perl has a section discussing this problem. It's worth reading for other reasons, too. Commented Feb 4, 2014 at 14:40
  • 1
    What's the problem you're trying to solve, what's the question? Commented Feb 4, 2014 at 14:40
  • There's no built-in way to generate matching strings from a regular expression in JavaScript. You'd have to write code to do it, and there are definitely better ways to do it than to generate random strings and see whether they match. It's a non-trivial problem however. Commented Feb 4, 2014 at 14:41
  • I wish to generate strings that match a regex. Commented Feb 4, 2014 at 14:41
  • 2
    Possible duplicate of Generate a random string based on a regular expression Commented Apr 12, 2017 at 18:59

2 Answers 2

16

If you're using JavaScript, there's Randexp which generates random strings that match a given regex.

Releases for browser

Sign up to request clarification or add additional context in comments.

1 Comment

Randexp generates only one random string from a regex. To generate every possible match, you can use genexp.js instead.
5

Use randexp.js to generate random strings from a regular expression:

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.