简体   繁体   English

Ruby:在字符串数组中查找日期

[英]Ruby : Find a Date in a array of strings

I am searching through an array of strings looking for a Date :我正在搜索一个字符串数组以查找Date

Is the method I'm using a good way to do it?我正在使用的方法是一种好方法吗? OR . . . . . is there a better alternative.有没有更好的选择。

Perhaps a more "beautiful" way to do it?也许是一种更“美丽”的方式来做到这一点?

    query = {'Hvaða','mánaðardagur','er','í','dag?','Það','er','02.06.2011','hví','spyrðu?'}

    def has_date(query)
        date = nil
        query.each do |q|
            begin
                date = Date.parse(q)
                query.delete(q)
                break
            rescue
            end
       end
       return date
    end

Note that in Ruby we use square brackets [] for array literals (curly braces {} are for Hash literals).请注意,在 Ruby 中,我们使用方括号[]表示数组文字(花括号{}用于 Hash 文字)。

Here is a solution that will find all dates in the array and return them as strings (thanks @steenslag):这是一个解决方案,它将查找数组中的所有日期并将它们作为字符串返回(感谢@steenslag):

require 'date'
arr = ['Hvaða', 'er', '02.06.2011', 'hví', '2011-01-01', '???']
dates = arr.select { |x| Date.parse(x) rescue nil }
dates # => ["02.06.2011", "2011-01-01"]

First you can try to validate the string, if it's a valid date format then you can parse it as a date:首先,您可以尝试验证字符串,如果它是有效的日期格式,那么您可以将其解析为日期:

query.each do |item|
  if item =~ /^\d{2}([-\\\/.])\d{2}\1\d{4}$/ then
    # coding
  end
end

If you just want the first date and you want to be strict about a valid date:如果您只想要第一次约会并且想要严格限制有效日期:

arr = ['Hvaða', 'er', '02.06.2011', 'hví', '2011-01-01', '???']

date = arr.detect do |x|  ## or find
  d,m,y = x.split('.')
  Date.valid_civil?(y.to_i, m.to_i, d.to_i)
end

p date #=> "02.06.2011"

(Date.parse is forgiving, it happily parses 02.13.2011) (Date.parse 是宽容的,它愉快地解析 02.13.2011)

If you want to parse more types of dates, use Chronic ... I think it also has the side effect of not raising errors, just returns nil.如果要解析更多类型的日期,请使用Chronic ... 我认为它还有不引发错误的副作用,只是返回 nil。

So if you want all valid dates found:因此,如果您想找到所有有效日期:

arr = ['Hvaða', 'er', '02.06.2011', 'hví', '2011-01-01', '???']
arr.collect {|a| Chronic.parse a}.compact

If you want the first:如果你想要第一个:

arr.find {|a| Chronic.parse a}

and if you just want a true/false "is there a date here?"如果你只想要一个真/假“这里有约会吗?”

arr.any? {|a| Chronic.parse a}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM