Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random string based on Regex?

I wonder if there is a way to generate random string from a regex like:

/[a-z0-9]{5}/.to_s
#=> "dsar3"

I found randexp (https://github.com/benburkert/randexp) but it seems to not work with a basic example like above and anyway I feel it's left abandoned.

Anyone?

like image 671
Hartator Avatar asked Apr 07 '13 06:04

Hartator


People also ask

How do you create a string in regex?

Just enter your regexp in the field below, press the Generate Text button, and you'll get a random text that matches your regexp. Press a button – invert a regexp. No ads, nonsense, or garbage.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What does (? I do in regex?

(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.


2 Answers

Perl has a CPAN module that can do this. It works by converting the regex into a generative grammar. The concept can probably be adapted to Ruby, but would be a little work.

See http://metacpan.org/pod/Parse::RandGen and http://metacpan.org/pod/Parse::RandGen::Regexp

like image 170
Neil Slater Avatar answered Oct 21 '22 06:10

Neil Slater


No but how about:

(0..255).map(&:chr).select{|x| x =~ /[a-z0-9]/}.sample(5).join
#=> "qif0l"
like image 23
pguardiario Avatar answered Oct 21 '22 06:10

pguardiario