Ruby gsub不会逃避单引号
我不明白这里发生了什么。 我应该如何提供gsub来获取字符串“Yaho \’o”?
>> "Yaho'o".gsub("Y", "\\Y") => "\\Yaho'o" >> "Yaho'o".gsub("'", "\\'") => "Yahooo"
\’意味着”这是比赛后的一切。 再次逃离\它的工作原理
"Yaho'o".gsub("'", "\\\\'")
"Yaho'o".gsub("'", "\\\\'")
因为您正在逃避转义字符以及转义单引号。
这也会做到,而且它更具可读性:
def escape_single_quotes(str) str.gsub(/'/) { |x| "\\#{x}" } end
如果你想要转义单引号和反斜杠,以便可以将该字符串嵌入双引号的ruby字符串中,那么以下内容将为您执行此操作:
def escape_single_quotes_and_backslash(str) str.gsub(/\\|'/) { |x| "\\#{x}" } end