在 Ruby 中转义字符串中的双反斜杠和单反斜杠
我正在尝试以这样的格式访问 Windows 平台上 ruby 脚本中的网络路径。
\\servername\some windows share\folder 1\folder2\
现在,如果我尝试使用它作为路径,它将不起作用。此脚本未正确转义单个反斜杠。
path = "\\servername\some windows share\folder 1\folder2\"
d = Dir.new(path)
我尝试了一切我能想到的方法来正确地避开路径中的斜线。然而我无法逃避那个反斜杠——因为它有特殊的含义。我尝试过单引号、双引号、转义反斜杠本身、使用备用引号(例如 %Q{} 或 %q{})、使用 ascii 到 char 转换。从某种意义上说,如果我做得不对,那么一切都不起作用。 :-) 现在的临时解决方案是映射一个网络驱动器 N:\ 指向该路径并以这种方式访问它,但这不是解决方案。
有谁知道如何正确转义单反斜杠?
谢谢
I'm trying to access a network path in my ruby script on a windows platform in a format like this.
\\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.
Does anyone have any idea how to properly escape single backslashes?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需将每个反斜杠加倍即可,如下所示:
Just double-up every backslash, like so:
试试这个
只要您使用单引号来定义字符串(例如,
'foo'
),就不需要转义单个\
。 除了以下两种情况\\
本身会生成一个\
。因此,\\\\
将为您提供所需的起始\\
。\
将尝试转义结束引号,因此您还需要一个\\
。或者,
您可以为自己定义一个优雅的助手。您可以将
/
与如下方法结合使用,而不是使用笨重的\
路径分隔符:Sweet!
Try this
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\\
works itself out to a single\
. So,\\\\
will give you the starting\\
you need.\
at the end of your path will tries to escape the closing quote so you need a\\
there as well.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:Sweet!