使用Gsub逃避撇号

时间:2011-06-27 22:00:57

标签: ruby regex gsub

我在Ruby工作,我正在尝试将'个字符转义为\',以便我可以在SQL中使用它们。我正在尝试使用gsub,但它似乎没有用。

"this doesn't work".gsub /'/, '\\'' #=> "this doesnt workt work"
"this doesn't work".gsub /'/, '\\\'' #=> "this doesnt workt work"
"this doesn't work".gsub /'/, '\\\\'' #=> "this doesn\\'t work"
"this doesn't work".gsub /'/, '\\\\\'' #=> "this doesn\\'t work"

我不知道gsub是否是正确使用的方法,所以我愿意尝试几乎任何可以获得我正在寻找的结果的东西。

2 个答案:

答案 0 :(得分:3)

由于Ruby正则表达式中的特殊含义/解释,其他人都有这个问题。

  

\'表示$',这就是之后的一切   比赛。再次逃离\它   作品

请参阅this answer

这有用吗?

"this doesn't work".gsub /'/, '\\\\\'' => "this doesn\\'t work"

答案 1 :(得分:0)

你必须逃避\和'。 当你需要'在结果中时,为什么不用“

定义结果
puts "this doesn't work".gsub /'/, "\\\\'" #=> "this doesn\'t work"
无论如何,

\必须逃脱。