Dave
Dave

Reputation: 19110

How do I build a regular expression from an array?

Using Ruby 2.4, how do I build a regular expression using an array that contains strings? I have

TOKENS = %w(to - &).freeze

I want to build a regular expression that says, match at least one number, an arbitrary of breaking or non-breaking space, and then one of the strings from my array. I tried teh below, with the resulting error

2.4.0 :014 > "abc" =~ /^\d+[[:space:]]*#{Regexp.escape(TOKENS)}/
TypeError: no implicit conversion of Array into String
    from (irb):14:in `escape'
    from (irb):14
    from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands/console.rb:65:in `start'
    from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands/console_helper.rb:9:in `start'
    from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:78:in `console'
    from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!'
    from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands.rb:18:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

An example of something that would match would be

2 to blah

and something that would not match would be

& no way

Upvotes: 3

Views: 1157

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

Use Regexp.union:

Return a Regexp object that is the union of the given patterns, i.e., will match any of its parts. The patterns can be Regexp objects, in which case their options will be preserved, or Strings. If no patterns are given, returns /(?!)/.

Note if there are any special chars, they will get escaped to match literal chars.

So, use

"abc" =~ /^\d+[[:space:]]*#{Regexp.union(TOKENS)}/
                                   ^^^^^

In Ruby 2.4, you may use .match?:

 /^\d+[[:space:]]*#{Regexp.union(TOKENS)}/.match?('abc')
                           ^^^^^           ^^^^^^

Upvotes: 4

Related Questions