From: Marnen Laibow-Koser Date: 2010-01-30T22:52:10+09:00 Subject: Re: How do I use a variable in a regexp search string? Thomas Sawyer wrote: > On Jan 29, 10:38�pm, Harry Kakueki wrote: >> > I dont know how to use a variable in a regex searchstring. >> > ruby seems to only handle hardcoded serachstring in >> > regex's. � How do you do this. � My code is below. >> >> Does this help? >> >> str = "abcdef" >> searchstring = "cd" >> p str =~ /#{searchstring}/ > > You may need to escape: > > p str =~ /#{Regexp.escape(searchstring)}/ But note that #{} only makes sense if you're interpolating a variable into part of a regex -- say, /January #{year}/. If the variable is the whole regex, then it's more sensible to do Regex.new(searchstring). Best, -- Marnen Laibow-Koser http://www.marnen.org marnen@marnen.org -- Posted via http://www.ruby-forum.com/.