在 Ruby 中的字符串中转义双反斜杠和单反斜杠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2774808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:37:21  来源:igfitidea点击:

Escape double and single backslashes in a string in Ruby

ruby-on-railsrubyescapingbackslash

提问by konung

I'm trying to access a network path in my ruby script on a windows platform in a format like this.

我正在尝试以这样的格式在 Windows 平台上访问我的 ruby​​ 脚本中的网络路径。

\servername\some windows share\folder 1\folder2\

Now If I try to use this as a path, it won't work. Single backslashes are not properly escaped for this script.

现在,如果我尝试将其用作路径,它将不起作用。此脚本未正确转义单个反斜杠。

path = "\servername\some windows share\folder 1\folder2\"
d = Dir.new(path)

I tried everything I could think of to properly escape slashes in the path. However I can't escape that single backslash - because of it's special meaning. I tried single quotes, double quotes, escaping backslash itself, using alternate quotes such as %Q{} or %q{}, using ascii to char conversion. Nothing works in a sense that I'm not doing it right. :-) Right now the temp solution is to Map a network drive N:\ pointing to that path and access it that way, but that not a solution.

我尝试了所有我能想到的方法来正确地避开路径中的斜线。但是我无法逃避那个反斜杠 - 因为它的特殊含义。我尝试了单引号、双引号、转义反斜杠本身、使用替代引号(例如 %Q{} 或 %q{}),以及使用 ascii 到 char 的转换。从某种意义上说,我没有做对,没有任何作用。:-) 现在临时解决方案是映射网络驱动器 N:\ 指向该路径并以这种方式访问​​它,但这不是解决方案。

Does anyone have any idea how to properly escape single backslashes?

有谁知道如何正确转义单个反斜杠?

Thank you

谢谢

回答by John Douthat

Just double-up every backslash, like so:

只需将每个反斜杠加倍,如下所示:

"\\servername\some windows share\folder 1\folder2\"

回答by ma?ek

Try this

尝试这个

puts '\\servername\some windows share\folder 1\folder2\'
#=> \servername\some windows share\folder 1\folder2\

So long as you're using single quotes to define your string(e.g., 'foo'), a single \does not need to be escaped. except in the following two cases

只要您使用单引号来定义字符串(例如,'foo'),\就不需要对单引号进行转义。除了以下两种情况

  1. \\works itself out to a single \. So, \\\\will give you the starting \\you need.
  2. The trailing \at the end of your path will tries to escape the closing quote so you need a \\there as well.
  1. \\自行解决一个单一的\. 所以,\\\\会给你\\你需要的开始。
  2. \路径末尾的尾随将尝试逃避结束引号,因此您也需要\\那里。


Alternatively,

或者,

You could define an elegant helper for yourself. Instead of using the clunky \path separators, you could use /in conjunction with a method like this:

您可以为自己定义一个优雅的助手。\您可以/与这样的方法结合使用,而不是使用笨重的路径分隔符:

def windows_path(foo)
  foo.gsub('/', '\')
end

puts windows_path '//servername/some windows share/folder 1/folder2/'
#=> \servername\some windows share\folder 1\folder2\

Sweet!

甜的!