Generate string for Regex pattern in Ruby

痴心易碎 提交于 2019-12-03 11:33:53
Малъ Скрылевъ

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)

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

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

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

Maybe you can find what you are looking for over here.

UPDATE: Now regular expressions supported in string_pattern gem and it is 30 times faster than other gems

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

To see a comparison of speed https://repl.it/@tcblues/Comparison-generating-random-string-from-regular-expression


I created a simple way to generate strings using a pattern without the mess of regular expressions, take a look at the string_pattern gem project: https://github.com/MarioRuiz/string_pattern

To install it: gem install string_pattern

This is an example of use:

# four characters. optional: capitals and numbers, required: lower
"4:XN/x/".gen    # aaaa, FF9b, j4em, asdf, ADFt
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!