Generate random string based on Regex?

2019-02-07 04:03发布

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?

2条回答
别忘想泡老子
2楼-- · 2019-02-07 04:53

No but how about:

(0..255).map(&:chr).select{|x| x =~ /[a-z0-9]/}.sample(5).join
#=> "qif0l"
查看更多
▲ chillily
3楼-- · 2019-02-07 05:06

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

查看更多
登录 后发表回答