tags:

views:

64

answers:

1

In PHP you need to use preg_quote() to escape all the characters in a string that have a particular meaning in a regular expression, to allow (in example) preg_match() to search for those special characters.

What is the equivalent in Ruby of the following code?

// The content of this variable is obtained from user input, in example.
$search = "$var = 100";
if (preg_match('/' . preg_quote($search, '/') . ";/i")) {
  // …
}
+3  A: 

You want Regexp.escape.

str = "[...]"
re = /#{Regexp.escape(str)}/
"la[...]la[...]la".gsub(re,"") #=> "lalala"
sepp2k