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?
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.
$ 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.
(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.
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
No but how about:
(0..255).map(&:chr).select{|x| x =~ /[a-z0-9]/}.sample(5).join
#=> "qif0l"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With