以下实例方法采用文件路径并返回文件的前缀(分隔符之前的部分):
@separator = "@"
def table_name path
regex = Regexp.new("\/[^\/]+#{@separator}")
path.match(regex)[0].gsub(/^.|.$/,'').downcase.to_sym
end
table_name "bla/bla/bla/Prefix@invoice.csv"
# => :prefix
Run Code Online (Sandbox Code Playgroud)
到目前为止,此方法仅适用于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/Prefix@invoice.csv")
# RegexpError: premature end of char-class: /(\/|\)[^\/\]+@/
# Target result:
table_name("bla/bla/bla/Prefix@invoice.csv")
# => :prefix
table_name("bla\bla\bla\Prefix@invoice.csv")
# => :prefix
Run Code Online (Sandbox Code Playgroud)
我怀疑Ruby的字符串插值和转义是让我困惑的地方.
我如何更改正则表达式以使其在Unix和Windows上都能正常工作?