Ruby gsub doesn't escape single-quotes

微笑、不失礼 提交于 2019-11-26 14:12:38

问题


I don't understand what is going on here. How should I feed gsub to get the string "Yaho\'o"?

>> "Yaho'o".gsub("Y", "\\Y")
=> "\\Yaho'o"
>> "Yaho'o".gsub("'", "\\'")
=> "Yahooo"

回答1:


\' means $' which is everything after the match. Escape the \ again and it works

"Yaho'o".gsub("'", "\\\\'")



回答2:


"Yaho'o".gsub("'", "\\\\'")

Because you're escaping the escape character as well as escaping the single quote.




回答3:


This will also do it, and it's a bit more readable:

def escape_single_quotes(str)
  str.gsub(/'/) { |x| "\\#{x}" }
end

If you want to escape both a single-quote and a backslash, so that you can embed that string in a double-quoted ruby string, then the following will do that for you:

def escape_single_quotes_and_backslash(str)
  str.gsub(/\\|'/) { |x| "\\#{x}" }
end


来源:https://stackoverflow.com/questions/2180322/ruby-gsub-doesnt-escape-single-quotes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!