What is the Ruby equivalent of preg_quote ()?

In PHP, you need to use preg_quote()it to avoid all characters in a string that have a certain value in a regular expression to allow (for example) preg_match()to look for these special characters.

What is equivalent in Ruby to 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")) {
  //
}
+5
source share
1 answer

You want to Regexp.escape.

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

All Articles