Escape double and single backslashes in a string in Ruby

懵懂的女人 提交于 2019-11-29 02:57:12

问题


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


回答1:


Just double-up every backslash, like so:

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



回答2:


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

  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.

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!



来源:https://stackoverflow.com/questions/2774808/escape-double-and-single-backslashes-in-a-string-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!