如何用双反斜杠替换反斜杠?

发布于 2024-11-10 17:11:43 字数 109 浏览 3 评论 0原文

我试图用两个反斜杠替换字符串中的反斜杠,如下所示:

str.gsub!("\\", "\\\\")

但是,它没有任何作用。我很困惑...

I'm trying to replace backslashes in my string with two backslashes like so:

str.gsub!("\\", "\\\\")

But, it doesn't do anything. I'm confused...

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

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

发布评论

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

评论(1

潇烟暮雨 2024-11-17 17:11:43

请注意,这个答案是在 ruby​​ 1.9 的上下文中给出的。作为红宝石
2.0 有一个新的正则表达式引擎,它在该上下文中可能无效。

这有效:

str.gsub!("\\", "\\\\\\") 
str.gsub!("\\", "\\\\\\\\") # also, will always work

编辑:解释(通过 http://www.ruby-forum.com/topic/143645 提供by @vache)

免责声明:我不熟悉 ruby​​ 正则表达式引擎的内部工作原理,这里的任何信息都是从上面提到的文章中扣除的。

要知道的基本事情是替换字符串会被评估两次。

斜杠第一次在字符串中作为转义符发挥作用,第二次 gsub 将在字符串中搜索组引用。

正如 @chris-johnsen 提到的,6 个斜杠并不总是有效。这让我相信类似的事情正在发生:

6 次斜线。 3 个斜杠被传递到组参考图层。尾部斜杠不被解释为转义字符,因为它后面没有任何内容,它被解释为反斜杠。所以最后这一层返回 2 个斜杠。如果后面有任何内容,则表达式将失败,因为第三个斜杠现在将用作转义字符。

对于 8 个斜线:4 个斜线将传递到组参考图层。四个斜线将依次减少为两个。

Note that this answer was givin in the contect of ruby 1.9. As ruby
2.0 has a new regex engine it might not be valid in that context.

This works:

str.gsub!("\\", "\\\\\\") 
str.gsub!("\\", "\\\\\\\\") # also, will always work

Edit: Explanation (via http://www.ruby-forum.com/topic/143645 provided by @vache)

Disclaimer: I'm not familiar with the inner workings of ruby's regex engine, any info here is deducted from the article mentioned above.

The basic thing to know is that the replacement string gets evaluated 2 times.

The first time the slashes do their job as escapes in the string, in the second time gsub will search the string for group references.

as @chris-johnsen mentioned, 6 slashes do not alway work. This leads me to believe something like this is happening:

For 6 slashes. 3 slashes are passed to the group reference layer. The trailing slash is interpreted not as an escape character because nothing is coming after it, it is interpreted as a backslash. So finally this layer returns 2 slashes. If anything would be trailing it, the expression will fail, as the third slash will now function as an escape character.

For 8 slashes: 4 slashes are passed to the group reference layer. The four slashes will in turn be reduced to two.

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