使用 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 是否是正确的方法,所以我愿意尝试几乎任何可以获得我正在寻找的结果的方法。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于 Ruby 正则表达式中的特殊含义/解释,其他人也遇到了这个问题。
请参阅此答案。
这有效吗?
Someone else had this very issue, due to a special meaning/interpretation in Ruby's regex.
See this answer.
Does this work?
您必须转义 \ 和 '。
当您需要结果中的 ' 时,为什么不使用 " 定义结果
\ 无论如何都必须转义。
You must escape the \ and the '.
When you need the ' in the result, why not define the result with "
\ must be escaped anyway.