【发布时间】:2011-07-03 09:02:59
【问题描述】:
以下实例方法采用文件路径并返回文件的前缀(分隔符之前的部分):
@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
到目前为止,此方法仅适用于 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
我怀疑 Ruby 的字符串插值和转义是让我感到困惑的地方。
如何更改正则表达式以使其同时在 Unix 和 Windows 上运行?
【问题讨论】:
-
我认为有一个 Ruby 常量可以处理这个问题 - 在 Unix 中是
/,在 Windows 中是 ``。