Ruby 用单反斜杠替换双反斜杠 [英] Ruby replace double backslash with single backslash
问题描述
我似乎无法在 Ruby 中用单个反斜杠替换双反斜杠.我想我可以用另一个反斜杠来逃避反斜杠.
I cannot seem to replace a double backslash with a single backslash in Ruby. I figured I would just escape the backslashes with another backslash.
1.9.3-p194 :001 > line = "this\\is\\a\\test"
=> "this\\is\\a\\test"
1.9.3-p194 :002 > line.gsub("\\\\", "\\") # Nothing
=> "this\\is\\a\\test"
那行不通,所以我决定尝试找到至少可以替代的匹配项.
That didn't work so I decided to try and find a match that at least makes a replacement.
1.9.3-p194 :003 > line.gsub("\\", "_") # This works for replacing \\
=> "this_is_a_test"
1.9.3-p194 :004 > line.gsub("\\", "\\") # Nothing
=> "this\\is\\a\\test"
我仍然找不到在 Ruby 中执行此操作的简单方法.
I still cannot find an easy way to do this in Ruby.
推荐答案
有了这行...
line = "this\\is\\a\\test"
...您实际上创建了一个如下所示的字符串:
... you actually create a string looking like this:
this\is\a\test
... 因为每个 \\
将被识别为单个斜杠.当然,您将无法替换双斜线,因为您的字符串中没有.
... as each \\
will be recognized as a single slash. Of course, you won't be able to replace double slashes, as there's none in your string.
line.gsub("\\", "_")
行就是这样做的:用 _<替换字符串中的所有 single 斜线/code> 符号.
line.gsub("\\", "_")
line is doing just that: replacing all the single slashes in your string with _
symbol.
line.gsub("\\", "\\")
只是伪装的空操作.
这篇关于Ruby 用单反斜杠替换双反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!