Generate a string for a Regex template in Ruby

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

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

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

But in Ruby, I did not find anything.

So how do you create a string for a regular expression pattern in Ruby (reverse regular expression)?

I want something 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 should be the correct string available in my regex pattern. Here the outputs were: tvvd, yt, bgdf6, 564fb , which generated their "example". I need this method.

Thank you for your advice.

+6
5

Ruby:

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

Regexp, Regexp, String, Regexp #to_s. , ., :

( (? opts: source). Regexp:: new , .

, Regexp #inspect, :

rxp.

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

:, Regexp String, , , . , ( , #split), grep :

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

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

:

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

#scan :

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

, , , , , ruby-string-random. :

Regexp.

:

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

, - stackoverflow - , :

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']
+5

, , . .

+1

Faker https://github.com/stympy/faker, :

 Faker::Base.regexify(/[a-z0-9]{10}/)
+1

: string_pattern, 30 ,

require 'string_pattern'
/[a-z0-9]+/.generate

https://repl.it/@tcblues/Comparison-generating-random-string-from-regular-expression


I created an easy way to generate strings using a pattern without messing up regular expressions, take a look at the gem string_pattern project: https://github.com/MarioRuiz/string_pattern

To install it: gem install string_pattern

This is a usage example:

# four characters. optional: capitals and numbers, required: lower
"4:XN/x/".gen    # aaaa, FF9b, j4em, asdf, ADFt
-1
source

All Articles