Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate string for Regex pattern in Ruby

In Python language I find rstr that can generate a string for a regex pattern.

Or in Python we have this method that can return range of string:

re.sre_parse.parse(pattern)
#..... ('range', (97, 122)) ....

But In Ruby I didn't find any thing.

So how to generate string for a regex pattern in Ruby(reverse regex)?

I wanna to some thing like this:

"/[a-z0-9]+/".example
#tvvd
"/[a-z0-9]+/".example
#yt
"/[a-z0-9]+/".example
#bgdf6
"/[a-z0-9]+/".example
#564fb

"/[a-z0-9]+/" is my input. The outputs must be correct string that available in my regex pattern. Here outputs were: tvvd , yt , bgdf6 , 564fb that "example" method generated them. I need that method.

Thanks for your advice.

like image 591
mortymacs Avatar asked Jan 13 '14 05:01

mortymacs


2 Answers

A bit late to the party, but - originally inspired by this stackoverflow thread - I have created a powerful ruby gem which solves the original problem:

https://github.com/tom-lord/regexp-examples

/this|is|awesome/.examples #=> ['this', 'is', 'awesome']
/https?:\/\/(www\.)?github\.com/.examples #=> ['http://github.com', 'http://www.github.com', 'https://github.com', 'https://www.github.com']
like image 174
Tom Lord Avatar answered Sep 25 '22 10:09

Tom Lord


You can also use the Faker gem https://github.com/stympy/faker and then use this call:

 Faker::Base.regexify(/[a-z0-9]{10}/)
like image 23
Fran Martinez Avatar answered Sep 24 '22 10:09

Fran Martinez