Interpolating a string into a regex

RubyRegex

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

Same as string insertion.

if goo =~ /#{Regexp.quote(foo)}/
#...

Solution 2 - Ruby

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.

Solution 3 - Ruby

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.

Solution 4 - Ruby

Regexp.compile(Regexp.escape(foo))

Solution 5 - Ruby

Use Regexp.new:

if goo =~ Regexp.new(foo) # Evaluates to /0.0.0.0/

Solution 6 - Ruby

Here's a limited but useful other answer:

I discovered I that I can easily insert into a regex without using Regexp.quote or Regexp.escape if I just used single quotes on my input string: (an IP address match)

IP_REGEX = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'

my_str = "192.0.89.234 blahblah text 1.2, 1.4" # get the first ssh key 
# replace the ip, for demonstration
my_str.gsub!(/#{IP_REGEX}/,"192.0.2.0") 
puts my_str # "192.0.2.0 blahblah text 1.2, 1.4"

single quotes only interpret \\ and \'.

http://en.wikibooks.org/wiki/Ruby_Programming/Strings#Single_quotes

This helped me when i needed to use the same long portion of a regex several times. Not universal, but fits the question example, I believe.

Solution 7 - Ruby

foo = "0.0.0.0"
goo = "here is some other stuff 0.0.0.0" 

puts "success!" if goo =~ /#{foo}/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris BunchView Question on Stackoverflow
Solution 1 - RubyJonathan LonowskiView Answer on Stackoverflow
Solution 2 - Rubyglenn mcdonaldView Answer on Stackoverflow
Solution 3 - RubyJasonTrueView Answer on Stackoverflow
Solution 4 - RubyMarkus JarderotView Answer on Stackoverflow
Solution 5 - RubyPaige RutenView Answer on Stackoverflow
Solution 6 - RubyPlasmarobView Answer on Stackoverflow
Solution 7 - RubyMike BreenView Answer on Stackoverflow