什么是相当于preg_quote()的Ruby等价物?

kia*_*uno 5 ruby regex

在PHP中,您需要使用preg_quote()以转义字符串中具有正则表达式中特定含义的所有字符,以允许(例如)preg_match()搜索这些特殊字符.

以下代码在Ruby中的等价物是什么?

// The content of this variable is obtained from user input, in example.
$search = "$var = 100";
if (preg_match('/' . preg_quote($search, '/') . ";/i")) {
  // …
}
Run Code Online (Sandbox Code Playgroud)

sep*_*p2k 6

你想要的Regexp.escape.

str = "[...]"
re = /#{Regexp.escape(str)}/
"la[...]la[...]la".gsub(re,"") #=> "lalala"
Run Code Online (Sandbox Code Playgroud)