Ruby中与preg_quote()等效的方法是什么?

5
在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")) {
  // …
}
1个回答

6
你需要使用Regexp.escape
str = "[...]"
re = /#{Regexp.escape(str)}/
"la[...]la[...]la".gsub(re,"") #=> "lalala"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接