Interpolating a string into a regex
I need to substitute the value of a string into my regular expression in Ruby. Is there an easy way to do this? For example:
foo = "0.0.0.0"
goo = "here is some other stuff 0.0.0.0"
if goo =~ /value of foo here dynamically/
puts "success!"
end
Solution 1:
Same as string insertion.
if goo =~ /#{Regexp.quote(foo)}/
#...
Solution 2:
Note that the Regexp.quote
in Jon L.'s answer is important!
if goo =~ /#{Regexp.quote(foo)}/
If you just do the "obvious" version:
if goo =~ /#{foo}/
then the periods in your match text are treated as regexp wildcards, and "0.0.0.0"
will match "0a0b0c0"
.
Note also that if you really just want to check for a substring match, you can simply do
if goo.include?(foo)
which doesn't require an additional quoting or worrying about special characters.