Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random string based on a regular expression

Tags:

javascript

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)
like image 227
Exception Avatar asked Jan 22 '12 08:01

Exception


2 Answers

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... http://fent.github.com/randexp.js/

like image 72
Billy Moon Avatar answered Sep 21 '22 06:09

Billy Moon


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.

like image 38
Ethan Avatar answered Sep 21 '22 06:09

Ethan