This isn't a Ruby question per se, it's how to construct a regex pattern that accomplishes what you want.
In "regex-ese", /pattern[:key]/
means:
- Find
pattern
. - Following
pattern
look for one of:
,k
,e
ory
.
Ruby doesn't automatically interpolate variables in strings or regex patterns like Perl does, so, instead, we have to mark where the variable is using #{...}
inline.
If you're only using /pattern[:key]/
as a pattern, don't bother interpolating it into a pattern. Instead, take the direct path and let Regexp do it for you:
pattern[:key] = 'foo'
Regexp.new(pattern[:key])
=> /foo/
Which is the same result as:
/#{pattern[:key]}/
=> /foo/
but doesn't waste CPU cycles.
Another of your attempts used .
, [
and ]
, which are reserved characters in patterns, used to help define patterns. If you need to use such characters, you can have Ruby's Regexp.escape
add \
escape characters appropriately, preserving their normal/literal meaning in the string:
Regexp.escape('5.7.1 [abc]')
=> "5\\.7\\.1\\ \\[abc\\]"
which, in real life is "5\.7\.1\ \[abc\]"
(when not being displayed in IRB)
To use that in a regex, use:
Regexp.new(Regexp.escape('5.7.1 [abc]'))
=> /5\.7\.1\ \[abc\]/