使用 Gsub 转义撇号

发布于 2024-11-17 13:29:57 字数 469 浏览 5 评论 0原文

我正在使用 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 是否是正确的方法,所以我愿意尝试几乎任何可以获得我正在寻找的结果的方法。

I'm working in Ruby and I'm trying to escape ' characters to \' so that I can use them in SQL. I'm trying to use gsub, but it doesn't seem to be working.

"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"

I don't know if gsub is even the right method to be using, so I'm willing to try almost anything that gets the results I'm looking for.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝海 2024-11-24 13:29:57

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

\' 表示 $' 后面的所有内容
比赛。再次转义 \ 即可
作品

请参阅此答案

这有效吗?

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

Someone else had this very issue, due to a special meaning/interpretation in Ruby's regex.

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

See this answer.

Does this work?

"this doesn't work".gsub /'/, '\\\\\'' => "this doesn\\'t work"
梨涡 2024-11-24 13:29:57

您必须转义 \ 和 '。
当您需要结果中的 ' 时,为什么不使用 " 定义结果

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

\ 无论如何都必须转义。

You must escape the \ and the '.
When you need the ' in the result, why not define the result with "

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

\ must be escaped anyway.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文