Generate random string based on Regex?

2019-02-07 04:17发布

问题:

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?

回答1:

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



回答2:

No but how about:

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