Generate String for Regex Pattern in Ruby

Generate string for Regex pattern in Ruby

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)

Generate random string based on Regex?

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

Create regular expression from string

s = "func:[sync] displayPTS"
# => "func:[sync] displayPTS"
r = Regexp.new(s)
# => /func:[sync] displayPTS/
r = Regexp.new(Regexp.escape(s))
# => /func:\[sync\]\ displayPTS/

Variable containing regex as string/generating regex dynamically and trouble with \b

This isn't hard, but it appears you're making it that way:

foo = '\b[ab]'
Regexp.new(foo) # => /\b[ab]/
/#{foo}/ # => /\b[ab]/

or:

foo = "\\b[ab]"
Regexp.new(foo) # => /\b[ab]/
/#{foo}/ # => /\b[ab]/

Ruby is perfectly happy to use a string to create a pattern, you just have to do it right.

Strings are great building blocks for patterns because we can build patterns up from smaller pieces, then finally join the pieces we want into a large pattern. We do that in all sorts of languages too, not just Ruby.

WORD_BOUNDARY = '\b'
WORD_CHARACTERS = '[a-zA-Z]'
WORD_PATTERN = /#{WORD_BOUNDARY}#{WORD_CHARACTERS}+#{WORD_BOUNDARY}/
WORD_PATTERN # => /\b[a-zA-Z]+\b/

/#{WORD_PATTERN}/ # => /(?-mix:\b[a-zA-Z]+\b)/
Regexp.new(WORD_PATTERN) # => /\b[a-zA-Z]+\b/

It's also important to note the difference between "\b" and '\b'. If the string allows interpolation of variables and escaped values, then \b will be treated as a backspace. That's NOT what you want:

"\b" # => "\b"
"\b".ord # => 8

Instead, use a non-interpreted string:

'\b' # => "\\b"

Or double-escape the word-boundary characters.

You can easily dynamically generate a pattern, you just have to follow the rules for string interpolation and understand that escaped characters have to be double-escaped if the string is interpolated.

How to generate a random string in Ruby

(0...8).map { (65 + rand(26)).chr }.join

I spend too much time golfing.

(0...50).map { ('a'..'z').to_a[rand(26)] }.join

And a last one that's even more confusing, but more flexible and wastes fewer cycles:

o = [('a'..'z'), ('A'..'Z')].map(&:to_a).flatten
string = (0...50).map { o[rand(o.length)] }.join

If you want to generate some random text then use the following:

50.times.map { (0...(rand(10))).map { ('a'..'z').to_a[rand(26)] }.join }.join(" ")

this code generates 50 random word string with words length less than 10 characters and then join with space

Converting a regular expression to a string in Ruby

From a response on a related SO question - Matt Aimonetti's randexp might be of some use. Not generalised to all regexp though...

EDIT: This version looks more up-to-date.

Find strings that match two regular expressions

Is there a quick way in general? No. What are "all the strings" that match these pairs of regular expressions:

  • /.*/ and /\d*/? (There are infinitely many!)
  • /\A\d{10}\z/ and /\A[0-8]{10}\z/? (There are 3,486,784,401!)
  • /\w+\d{2,4}@?([[:punct:]]|\w){2}/ and /(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)/ (I haven't even tried to work this out; my point is: you could provide arbitrarily complicated input!!)

...But for simple scenarios, such as what you've actually asked, it would be feasible to use this ruby gem:

/^A+\S{2}$/.examples(max_group_results: 999) & /^AB+\d{1}$/.examples(max_group_results: 999)
=> ["AB0", "AB1", "AB2", "AB3", "AB4", "AB5", "AB6", "AB7", "AB8", "AB9"]

How to match any pattern to a any string using Ruby?

You can use capture groups and backreferences to match the same substring multiple times, e.g.:

abab = /\A(.+)(.+)\1\2\z/
aabb = /\A(.+)\1(.+)\2\z/
aaaa = /\A(.+)\1\1\1\z/

'dogcatdogcat'.match?(abab) #=> true
'dogcatdogcat'.match?(aabb) #=> false
'dogcatdogcat'.match?(aaaa) #=> false

'carcarhousehouse'.match?(abab) #=> false
'carcarhousehouse'.match?(aabb) #=> true
'carcarhousehouse'.match?(aaaa) #=> false

In the above pattern, (.+) defines a capture group that matches one or more characters. \1 then refers to the 1st capturing group and matches the same substring. (\2 is the 2nd group and so on)

\A and \z are anchors to match the beginning and end of the string.

Convert a string to regular expression ruby

Looks like here you need the initial string to be in single quotes (refer this page)

>> str = '[\w\s]+'
=> "[\\w\\s]+"
>> Regexp.new str
=> /[\w\s]+/


Related Topics



Leave a reply



Submit