10

Is there any way of generating random text which satisfies provided regular expression.
I am looking for a function which works like below

var reg = Some Regular Expression  
var str = RandString(reg)

4 Answers 4

14

I have seen fairly good solutions in perl and ruby on github, but I think there are technical issues that make a complete solution impossible. For example, /[0-9]+/ has an infinite upper bound, which is not practical for selecting random numbers from.

Never seen it in JavaScript, but you could translate.


EDIT: After googling for a few seconds... https://github.com/fent/randexp.js

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

1 Comment

Very useful answer and matches my requirement exactly.
1

if you know what the regular expression is, you can just generate random strings, then use a function that references the index of the letters and changes them as needed. Regex expressions vary widely, so it will be difficult to find one in particular that satisfies all possible regex.

Comments

1

Your question is pretty open so hopefully this steers you to the right solution. Get the current time (in seconds), MD5 it, check it against a REGEX, return the match.

Running Example: http://jsfiddle.net/MattLo/3gKrb/

Usage: RandString(/([A-Za-z])/ig); // expected to be a string

2 Comments

Very useful answer and closely related to my requirement.
The fiddle gives wrong out put.. Eg: /a/ig gives me aaa and aaaa as output when it should just be a. Tested with many other regex inputs and it breaks
1

For JavaScript, the following modules can generate a random match to a regex:

1 Comment

To generate all matches of a regex, you can also use genex.js.

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.