[英]How to check whether a string contains today's date in a specific format
我正在解析一些聚合給定城市中正在發生的事情的 RSS 提要。 我只對今天發生的事情感興趣。
目前我有這個:
require 'rubygems'
require 'rss/1.0'
require 'rss/2.0'
require 'open-uri'
require 'shorturl'
source = "http://rss.feed.com/example.xml"
content = ""
open(source) do |s| content = s.read end
rss = RSS::Parser.parse(content, false)
t = Time.now
day = t.day.to_s
month = t.strftime("%b")
rss.items.each do |rss|
if "#{rss.title}".include?(day)&&(month)
# does stuff with it
end
end
當然,通過檢查標題(我知道包含以下格式的事件日期:“(11 年 4 月 2 日)”)是否包含日期和月份(例如,'2' 和 'May')我也得到了信息關於 5 月 12 日、5 月 20 日等發生的事件。 我怎樣才能讓它萬無一失,只得到今天的事件?
這是一個示例標題:“Diggin Deeper @ The Big Chill House(2011 年 5 月 12 日)”
today = Time.now.strftime("%d:%b:%y")
if date_string =~ /(\d*).. (.*?) (\d\d)/
article_date = sprintf("%02i:%s:%s", $1.to_i, $2, $3)
if today == article_date
#this is today
else
#this is not today
end
else
raise("No date found in title.")
end
如果標題包含其他數字,可能會出現問題。 標題是否在日期周圍有任何邊界字符,例如日期前的連字符或它周圍的括號? 將這些添加到正則表達式可以防止麻煩。 你能給我們一個示例標題嗎? (另一種方法是使用 Time#strftime 創建一個與標題中顯示的日期完全匹配的字符串,然后只使用 String#include? 與該字符串,但我認為沒有一種優雅的方式當天的'th'/'nd'/'rd'/等。)
使用這樣的東西:
def check_day(date)
t = Time.now
day = t.day.to_s
month = t.strftime("%b")
if date =~ /^#{day}nd\s#{month}\s11/
puts "today!"
else
puts "not today!"
end
end
check_day "3nd May 11" #=> today!
check_day "13nd May 11" #=> not today!
check_day "30nd May 11" #=> not today!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.