我有一个如下所示的字符串:log/archive/2016-12-21.zip
,我需要提取日期部分。
到目前为止,我已尝试过这些解决方案:
1) ["log/archive/2016-12-21.zip"].map{|i|i[/\d{4}-\d{2}-\d{2}/]}.first
2) "log/archive/2016-12-21.zip".to_date
3) "log/archive/2016-12-21.zip".split("/").last.split(".").first
有更好的方法吗?
答案 0 :(得分:4)
您可以使用File.basename
传递扩展程序:
File.basename("log/archive/2016-12-21.zip", ".zip")
# => "2016-12-21"
如果您希望该值为Date
,只需使用Date.parse
将字符串转换为“日期”。
require 'date'
Date.parse(File.basename("log/archive/2016-12-21.zip", ".zip"))
答案 1 :(得分:1)
drv->probe()
如果您只想要日期字符串而不是日期对象,请按以下方式更改方法。
require 'date'
def pull_dates(str)
str.split(/[\/.]/).map { |s| Date.strptime(s, '%Y-%m-%d') rescue nil }.compact
end
pull_dates "log/archive/2016-12-21.zip"
#=> [#<Date: 2016-12-21 ((2457744j,0s,0n),+0s,2299161j)>]
pull_dates "log/2016-12-21/archive.zip"
#=> [#<Date: 2016-12-21 ((2457744j,0s,0n),+0s,2299161j)>]
pull_dates "log/2016-12-21/2016-12-22.zip"
#=> [#<Date: 2016-12-21 ((2457744j,0s,0n),+0s,2299161j)>,
# #<Date: 2016-12-22 ((2457745j,0s,0n),+0s,2299161j)>]
pull_dates "log/2016-12-21/2016-12-32.zip"
#=> [#<Date: 2016-12-21 ((2457744j,0s,0n),+0s,2299161j)>]
pull_dates "log/archive/2016A-12-21.zip"
#=> []
pull_dates "log/archive/2016/12/21.zip"
#=> []
答案 2 :(得分:1)
这个正则表达式应该涵盖大多数情况。它允许年,月,日之间的可选非数字:
require 'date'
def extract_date(filename)
if filename =~ /((?:19|20)\d{2})\D?(\d{2})\D?(\d{2})/ then
year, month, day = $1.to_i, $2.to_i, $3.to_i
# Do something with year, month, day, or just leave it like this to return an array : [2016, 12, 21]
# Date.new(year, month, day)
end
end
p extract_date("log/archive/2016-12-21.zip")
p extract_date("log/archive/2016.12.21.zip")
p extract_date("log/archive/2016:12:21.zip")
p extract_date("log/archive/2016_12_21.zip")
p extract_date("log/archive/20161221.zip")
p extract_date("log/archive/2016/12/21.zip")
p extract_date("log/archive/2016/12/21")
#=> Every example returns [2016, 12, 21]
答案 3 :(得分:0)
请试试这个
"log/archive/2016-12-21.zip".scan(/\d{4}-\d{2}-\d{2}/).pop
=> "2016-12-21"
如果日期格式无效,则返回nil。
实施例: -
"log/archive/20-12-21.zip".scan(/\d{4}-\d{2}-\d{2}/).pop
^^
=> nil
希望它有所帮助。