下面的實例方法需要一個文件路徑和返回文件的前綴(部分分離前):Ruby的正則表達式匹配UNIX和Windows的文件路徑
@separator = "@"
def table_name path
regex = Regexp.new("\/[^\/]+#{@separator}")
path.match(regex)[0].gsub(/^.|.$/,'').downcase.to_sym
end
table_name "bla/bla/bla/[email protected]"
# => :prefix
到目前爲止,此方法僅適用在Unix上。爲了使它在Windows上工作,我還需要捕獲反斜槓(\)。不幸的是,那個時候我卡住了:
@separator = "@"
def table_name path
regex = Regexp.new("(\/|\\)[^\/\\]+#{@separator}")
path.match(regex)[0].gsub(/^.|.$/,'').downcase.to_sym
end
table_name("bla/bla/bla/[email protected]")
# RegexpError: premature end of char-class: /(\/|\)[^\/\][email protected]/
# Target result:
table_name("bla/bla/bla/[email protected]")
# => :prefix
table_name("bla\bla\bla\[email protected]")
# => :prefix
我懷疑Ruby的字符串插值和逃避是什麼在這裏我混淆了。
如何更改正則表達式使其在Unix和Windows上都能正常工作?
我認爲有一個Ruby常量處理了這個問題 - 它在Unix中是'/',在Windows中是'\'。 –