7

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?

3
  • @iAmRubuuu This is not really random and is determined by a pattern instead. Commented Apr 7, 2013 at 7:20
  • It would need some basic constraints, right? I mean, there's no way to generate a random regex that matchs /.*/, since the number of characters involved could be any length between 0 an infinite. Should the number of characters be random also, or should we be trying to randomly select a value from an infinite set? Or are you suggesting a constraint wherein the regex could not allow things like * or + (as is the case with your example)? Commented Apr 14, 2013 at 23:58
  • Also, if you had .to_s on a regex provide a random matching string, that'd be a pretty serious wtf for the next developer that saw that code. Commented Apr 15, 2013 at 0:00

2 Answers 2

4

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

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

Comments

2

No but how about:

(0..255).map(&:chr).select{|x| x =~ /[a-z0-9]/}.sample(5).join
#=> "qif0l"

4 Comments

what the x =~ /[a-z0-9]/ is doing logically?
It's selecting only chars that match the regex
sample does not allow duplicates, so "qqf01" would never happen.
Well there's a simple workaround if you really need duplicates.

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.