简体   繁体   English

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

[英]How to replace backslash with double backslash?

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...我很困惑...

Note that this answer was givin in the contect of ruby 1.9.请注意,这个答案是在 ruby 1.9 的范围内给出的。 As ruby 2.0 has a new regex engine it might not be valid in that context.由于 ruby 2.0 具有新的正则表达式引擎,因此在该上下文中可能无效。

This works:这有效:

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

Edit: Explanation (via http://www.ruby-forum.com/topic/143645 provided by @vache)编辑:解释(通过http://www.ruby-forum.com/topic/143645由@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.免责声明:我不熟悉 ruby 正则表达式引擎的内部工作原理,这里的任何信息都是从上面提到的文章中扣除的。

The basic thing to know is that the replacement string gets evaluated 2 times.要知道的基本事情是替换字符串被评估了 2 次。

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.斜杠第一次作为字符串中的转义符完成其工作,第二次 gsub 将在字符串中搜索组引用。

as @chris-johnsen mentioned, 6 slashes do not alway work.正如@chris-johnsen 提到的,6 个斜线并不总是有效。 This leads me to believe something like this is happening:这让我相信这样的事情正在发生:

For 6 slashes.对于 6 个斜线。 3 slashes are passed to the group reference layer. 3 个斜线被传递到组参考层。 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.所以最后这一层返回 2 个斜线。 If anything would be trailing it, the expression will fail, as the third slash will now function as an escape character.如果后面有任何内容,则表达式将失败,因为第三个斜杠现在将 function 作为转义字符。

For 8 slashes: 4 slashes are passed to the group reference layer.对于 8 个斜线:4 个斜线被传递到组参考层。 The four slashes will in turn be reduced to two.四个斜线将依次减少到两个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM