替换 与 \'在鲁比?

发布于 2024-08-22 03:49:47 字数 172 浏览 7 评论 0原文

我正在尝试找出如何将 ' 之类的引号替换为 \' 之类的内容。

我该怎么做?

我已经尝试过

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

,但它只给出一个空字符串。我在这里做错了什么?

I'm trying to figure out how to replace a quote like ' with something like \'.

How would I do this?

I have tried

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

but it just gives an empty string. What am I doing wrong here?

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

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

发布评论

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

评论(5

请远离我 2024-08-29 03:49:47

这个怎么样

puts "'".gsub("'","\\\\'")
\'

原因是 \' 在 gsub(正则表达式)中表示 匹配后,因此需要用 \\' 和 \ 显然被转义为 \\,最终为 \\\\'

示例

>> "abcd".gsub("a","\\'")
=> "bcdbcd"

a 被替换为 a 之后的所有内容。

How about this

puts "'".gsub("'","\\\\'")
\'

The reason is that \' means post-match in gsub (regex) and because of that it needs to be escaped with \\' and \ is obviously escaped as \\, ending up with \\\\'.

Example

>> "abcd".gsub("a","\\'")
=> "bcdbcd"

a is replaced with everything after a.

一萌ing 2024-08-29 03:49:47

$' 变量是匹配项右侧的字符串。在 gsub 替换字符串中,相同的变量将是 \' ——这就是问题所在。

x = "'foo'"
x.gsub!(/'/, "\\'")
puts x.inspect        # foo'foo

这应该有效:

x = "'foo'"
x.gsub!(/'/, "\\\\'")
puts x.inspect
puts x

The $' variable is the string to the right of the match. In the gsub replacement string, the same variable would be \' -- hence the problem.

x = "'foo'"
x.gsub!(/'/, "\\'")
puts x.inspect        # foo'foo

This should work:

x = "'foo'"
x.gsub!(/'/, "\\\\'")
puts x.inspect
puts x
作妖 2024-08-29 03:49:47

这可能是一个错误......或者至少,它打破了我对最少惊喜原则的想法。

irb(main):039:0> "life's grand".gsub "'", "\\\'"
=> "lifes grands grand"
irb(main):040:0> "life's grand".gsub "'", "\\\\'"
=> "life\\'s grand"

That might be a bug.. Or at the very least, something which breaks MY idea of the principle of least surprise.

irb(main):039:0> "life's grand".gsub "'", "\\\'"
=> "lifes grands grand"
irb(main):040:0> "life's grand".gsub "'", "\\\\'"
=> "life\\'s grand"
南街女流氓 2024-08-29 03:49:47

我实际上使用过的两步方法......

BACKSLASH = 92.chr
temp = "'".gsub("'", "¤'")
puts temp.gsub("¤", BACKSLASH)
=> "\'"

只有在文本中明显不使用“¤”时才有效......

A two-step approach I've actually used...

BACKSLASH = 92.chr
temp = "'".gsub("'", "¤'")
puts temp.gsub("¤", BACKSLASH)
=> "\'"

Will only work if '¤' isn't used in the text obviously...

纸短情长 2024-08-29 03:49:47

这样做怎么样:

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

不太漂亮,但我认为它有效......

How about doing this :

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

Not pretty but I think it works...

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