本文介绍了preg_quote() 的 Ruby 等价物是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 PHP 中,您需要使用 preg_quote()
来转义字符串中在正则表达式中具有特定含义的所有字符,以允许(例如)preg_match()
来搜索那些特殊字符.
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.
以下代码在 Ruby 中的等价物是什么?
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")) {
// …
}
推荐答案
你想要Regexp.escape
.
str = "[...]"
re = /#{Regexp.escape(str)}/
"la[...]la[...]la".gsub(re,"") #=> "lalala"
这篇关于preg_quote() 的 Ruby 等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!