tags:

views:

2121

answers:

6

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 =~ /foo's value goes here/
  puts "success!"
end
+2  A: 

Use Regexp.new:

if goo =~ Regexp.new(foo) # Evaluates to /0.0.0.0/
yjerem
+4  A: 

probably Regexp.escape(foo) would be a starting point, but is there a good reason you can't use the more conventional expression-interpolation "my stuff #{mysubstitutionvariable}"?

Also, you can just use !goo.match(foo).nil? with a literal string.

JasonTrue
+2  A: 
Regex.compile(Regex.escape(foo))
MizardX
+11  A: 

Same as string insertion.

if goo =~ /#{Regexp.quote(foo)}/
#...
Jonathan Lonowski
+3  A: 
foo = "0.0.0.0"
goo = "here is some other stuff 0.0.0.0" 

puts "success!" if goo =~ /#{foo}/
Mike Breen
No, this will give an erroneous "true" for "here is some other stuff 070x0!0", because the dots are regexp wildcards.
glenn mcdonald
good catch glenn.
Mike Breen
+4  A: 

Note that the Regexp.quote in Jon L.'s version 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 "0x0y0z"...

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...

glenn mcdonald
Ah, great catch Glenn! Thanks!
Chris Bunch