gsub 中的反斜杠(转义和反向引用)

发布于 2024-09-05 13:50:41 字数 501 浏览 8 评论 0原文

考虑以下代码片段:

puts 'hello'.gsub(/.+/, '\0 \\0 \\\0 \\\\0')

此打印(如 ideone.com 上所示):

hello hello \0 \0

这非常令人惊讶,因为我期望看到类似这样的内容:

hello \0 \hello \\0

我的论点是 \ 是转义字符,因此您编写 \\ 来获得文字反斜杠,因此 \\0 是一个反斜杠 \ 后跟 0 等。显然这不是 gsub 的解释方式,所以有人可以解释一下这是怎么回事?

我需要做什么才能得到上面我想要的替代品?

Consider the following snippet:

puts 'hello'.gsub(/.+/, '\0 \\0 \\\0 \\\\0')

This prints (as seen on ideone.com):

hello hello \0 \0

This was very surprising, because I'd expect to see something like this instead:

hello \0 \hello \\0

My argument is that \ is an escape character, so you write \\ to get a literal backslash, thus \\0 is a literal backslash \ followed by 0, etc. Obviously this is not how gsub is interpreting it, so can someone explain what's going on?

And what do I have to do to get the replacement I want above?

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

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

发布评论

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

评论(1

提笔书几行 2024-09-12 13:50:41

使用单引号而不是双引号时,转义受到限制:

puts 'sinlge\nquote'
puts "double\nquote"

"\0" 是空字符(在 C 中用于确定字符串的结尾),其中 '\0 '"\\0",因此 'hello'.gsub(/.+/, '\0')'hello '.gsub(/.+/, "\\0") 返回 "hello",但 'hello'.gsub(/.+/, "\0" ) 返回“\000”。现在 'hello'.gsub(/.+/, '\\0') 返回 'hello' 是 ruby​​ 试图处理程序员不保留 single 和 single 之间的差异的问题记住双引号。事实上,这与 gsub 无关:'\0' == "\\0"'\\0' == "\\ 0”。遵循这个逻辑,无论您怎么想,这就是 ruby​​ 如何看待其他字符串: '\\\0''\\\\0' 相等"\\\\0",(打印时)为您提供 \\0。由于 gsub 使用 \x 来插入匹配号 x,因此您需要一种方法来转义 \x,即 \\x,或者在其字符串表示:"\\\\x"

因此这条线

puts 'hello'.gsub(/.+/, "\\0 \\\\0 \\\\\\0 \\\\\\\\0")

确实导致

hello \0 \hello \\0

Escaping is limited when using single quotes rather then double quotes:

puts 'sinlge\nquote'
puts "double\nquote"

"\0" is the null-character (used i.e. in C to determine the end of a string), where as '\0' is "\\0", therefore both 'hello'.gsub(/.+/, '\0') and 'hello'.gsub(/.+/, "\\0") return "hello", but 'hello'.gsub(/.+/, "\0") returns "\000". Now 'hello'.gsub(/.+/, '\\0') returning 'hello' is ruby trying to deal with programmers not keeping the difference between single and double quotes in mind. In fact, this has nothing to do with gsub: '\0' == "\\0" and '\\0' == "\\0". Following this logic, whatever you might think of it, this is how ruby sees the other strings: both '\\\0' and '\\\\0' equal "\\\\0", which (when printed) gives you \\0. As gsub uses \x for inserting match number x, you need a way to escape \x, which is \\x, or in its string representation: "\\\\x".

Therefore the line

puts 'hello'.gsub(/.+/, "\\0 \\\\0 \\\\\\0 \\\\\\\\0")

indeed results in

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