如何用双反斜杠替换反斜杠?
我试图用两个反斜杠替换字符串中的反斜杠,如下所示:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这有效:
编辑:解释(通过 http://www.ruby-forum.com/topic/143645 提供by @vache)
免责声明:我不熟悉 ruby 正则表达式引擎的内部工作原理,这里的任何信息都是从上面提到的文章中扣除的。
要知道的基本事情是替换字符串会被评估两次。
斜杠第一次在字符串中作为转义符发挥作用,第二次 gsub 将在字符串中搜索组引用。
正如 @chris-johnsen 提到的,6 个斜杠并不总是有效。这让我相信类似的事情正在发生:
6 次斜线。 3 个斜杠被传递到组参考图层。尾部斜杠不被解释为转义字符,因为它后面没有任何内容,它被解释为反斜杠。所以最后这一层返回 2 个斜杠。如果后面有任何内容,则表达式将失败,因为第三个斜杠现在将用作转义字符。
对于 8 个斜线:4 个斜线将传递到组参考图层。四个斜线将依次减少为两个。
This works:
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.