Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Ruby equivalent of preg_quote()?

Tags:

regex

ruby

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 (for 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")) {
  // …
}
like image 390
apaderno Avatar asked Jul 25 '10 12:07

apaderno


1 Answers

You want Regexp.escape.

str = "[...]"
re = /#{Regexp.escape(str)}/
"la[...]la[...]la".gsub(re,"") #=> "lalala"
like image 61
sepp2k Avatar answered Oct 22 '22 01:10

sepp2k