London
London

Reputation: 15274

Regexp union in ruby escapes my original regex

I've got multiple regexes and I want to use Regexp.union to combine them in one big regex so I have this regex to show as an example:

^image\d*$

So I try this :

regex = %w(^image\d*$)
=> ["^image\\d*$"]
re = Regexp.union(regex)
=> /\^image\\d\*\$/

And it escapes my regex to /\^image\\d\*\$/ so when I try the basic case it doesn't match :

"image0".match(re)
 => nil 

How can I get arround this?

Upvotes: 3

Views: 1733

Answers (1)

falsetru
falsetru

Reputation: 369054

Pass Regexp object. %w(...) is string literal. Use %r(...) or /.../ for regular expression literal.

regex = %r(^image\d*$)
# => /^image\d*$/
Regexp.union(regex)
# => /^image\d*$/

array_of_regexs = [/a/, /b/, /c/]
# => [/a/, /b/, /c/]
Regexp.union(array_of_regexs)
# => /(?-mix:a)|(?-mix:b)|(?-mix:c)/

Upvotes: 7

Related Questions