The simple starting place is:
words = %w[one two three]
/#{ Regexp.union(words).source }/i # => /one|two|three/i
You probably want to make sure you're only matching words so tweak it to:
/\b#{ Regexp.union(words).source }\b/i # => /\bone|two|three\b/i
For cleanliness and clarity I prefer using a non-capturing group:
/\b(?:#{ Regexp.union(words).source })\b/i # => /\b(?:one|two|three)\b/i
Using source
is important. When you create a Regexp object, it has an idea of the flags (i
, m
, x
) that apply to that object and those get interpolated into the string:
"#{ /foo/i }" # => "(?i-mx:foo)"
"#{ /foo/ix }" # => "(?ix-m:foo)"
"#{ /foo/ixm }" # => "(?mix:foo)"
or
(/foo/i).to_s # => "(?i-mx:foo)"
(/foo/ix).to_s # => "(?ix-m:foo)"
(/foo/ixm).to_s # => "(?mix:foo)"
That's fine when the generated pattern stands alone, but when it's being interpolated into a string to define other parts of the pattern the flags affect each sub-expression:
/\b(?:#{ Regexp.union(words) })\b/i # => /\b(?:(?-mix:one|two|three))\b/i
Dig into the Regexp documentation and you'll see that ?-mix
turns off "ignore-case" inside (?-mix:one|two|three)
, even though the overall pattern is flagged with i
, resulting in a pattern that doesn't do what you want, and is really hard to debug:
'foo ONE bar'[/\b(?:#{ Regexp.union(words) })\b/i] # => nil
Instead, source
removes the inner expression's flags making the pattern do what you'd expect:
/\b(?:#{ Regexp.union(words).source })\b/i # => /\b(?:one|two|three)\b/i
and
'foo ONE bar'[/\b(?:#{ Regexp.union(words).source })\b/i] # => "ONE"
You can build your patterns using Regexp.new
and passing in the flags:
regexp = Regexp.new('(?:one|two|three)', Regexp::EXTENDED | Regexp::IGNORECASE) # => /(?:one|two|three)/ix
but as the expression becomes more complex it becomes unwieldy. Building a pattern using string interpolation remains more easy to understand.