Generate string for Regex pattern in Ruby

random, regex, ruby, string

Solution

In Ruby:

/qweqwe/.to_s
# => "(?-mix:qweqwe)"

When you declare a `Regexp`, you've got the `Regexp` class object, to convert it to `String` class object, you may use `Regexp`'s method `#to_s`. During conversion the special fields will be expanded, as you may see in the example., using:

(using the (?opts:source) notation. This string can be fed back in to Regexp::new to a regular expression with the same semantics as the original.

Also, you can use `Regexp`'s method `#inspect`, which:

produces a generally more readable version of rxp.

/ab+c/ix.inspect        #=> "/ab+c/ix"

Note: that the above methods are only use for plain conversion `Regexp` into `String`, and in order to match or select set of string onto an other one, we use other methods. For example, if you have a sourse array (or string, which you wish to split with `#split` method), you can grep it, and get result array:

array = "test,ab,yr,OO".split( ',' )
# => ['test', 'ab', 'yr', 'OO']

array = array.grep /[a-z]/
 # => ["test", "ab", "yr"]

And then convert the array into string as:

array.join(',')
# => "test,ab,yr"

Or just use `#scan` method, with slightly changed regexp:

"test,ab,yr,OO".scan( /[a-z]+/ )
# => ["test", "ab", "yr"] 

However, if you really need a random string matched the regexp, you have to write your own method, please refer to the post, or use ruby-string-random library. The library:

generates a random string based on Regexp syntax or Patterns.

And the code will be like to the following:

pattern = '[aw-zX][123]'
result = StringRandom.random_regex(pattern)

Problem

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.

Original source

Related problems