Ruby 有人能帮我擦干这个REGEX吗?
这是我的第一个问题(尽管我在过去找到了许多关于堆栈溢出问题的完美解决方案——这是我寻求帮助的第一个来源) 我有包含一个月和一系列日期的文本字符串。有时,有两个月的时间Ruby 有人能帮我擦干这个REGEX吗?,ruby,regex,Ruby,Regex,这是我的第一个问题(尽管我在过去找到了许多关于堆栈溢出问题的完美解决方案——这是我寻求帮助的第一个来源) 我有包含一个月和一系列日期的文本字符串。有时,有两个月的时间 date1 = "January 9, 10, 15, 16, 17, 18, 22, 23, 24" date2 = "September 19, 20, 25, 26, 27, 28, October 2, 3, 4, 10, 11" 我写了一段非常湿的代码,从字符串中提取月份,然后添加每个日期,再加上年份。 然而,有几个问
date1 = "January 9, 10, 15, 16, 17, 18, 22, 23, 24"
date2 = "September 19, 20, 25, 26, 27, 28, October 2, 3, 4, 10, 11"
我写了一段非常湿的代码,从字符串中提取月份,然后添加每个日期,再加上年份。
然而,有几个问题我就是搞不清楚
require 'rubygems'
require 'nokogiri'
require 'open-uri'
date1 = "January 9, 10, 15, 16, 17, 18, 22, 23, 24"
date2 = "September 19, 20, 25, 26, 27, 28, October 2, 3, 4, 10, 11"
datetext = date1.scan(/([\w\-]+)/) #=> pulls the whole string
datetext2 = date1.scan(/(\w*)\s?/)[0] #=> this pulls the month
datenumbers = date1.scan(/(\d+)/)
firstdate = datenumbers[0] #=> the first date following the first month
seconddate = datenumbers[1]
year = "2014"
mdy1 = "#{datetext2} #{firstdate} #{year}"
mdy2 = "#{datetext2} #{seconddate} #{year}"
puts date1
puts " "
puts datetext2 #=> this variable adds the [0] delimiter to pull the 1st month
puts firstdate
puts " "
puts mdy1
puts mdy2
puts " "
我建议你做以下事情 代码
def extract_dates_by_month(str)
str.scan(/[A-Z][a-z]+|\d+/).each_with_object([]) { |e,b|
e[0][/[A-Z]/] ? b << [e,[]] : b.last.last << e }
end
str = "September 19, 20, 25, 26, October 2, 3, 4, 10, November 3, 12, 17"
extract_dates_by_month(str)
#=> [["September", ["19", "20", "25", "26"]],
# ["October", ["2", "3", "4", "10"]],
# ["November", ["3", "12", "17"]]]
解释
第一步是提取月份名称和日期:
a = str.scan(/[A-Z][a-z]+|\d+/)
#=> ["September", "19", "20", "25", "26", "October", "2", "3", "4", "10",
# "November", "3", "12", "17"]
然后,我们将此阵列分为几个月:
a.each_with_object([]) { |e,b| e[0][/[A-Z]/] ? b << [e,[]] : b.last.last << e }
#=> [["September", ["19", "20", "25", "26"]],
# ["October", ["2", "3", "4", "10"]],
# ["November", ["3", "12", "17"]]]
等等
如果希望天数为整数,请更改:
b.last.last << e
b.last.last Gary,这里有一些关于问题写作的建议:1。消除所有无关的语句(例如,此处的三个require
语句);2.当你给出一个例子(例子很好)时,一定要展示你想要的结果,如果适用的话,也要展示你得到的不正确的结果。谢谢你关于写作问题的建议,特别是你一步一步地告诉我你做了什么,Cary。我会试试你的建议,让你知道进展如何。哦,你问我想要的结果是什么。我想使用Time.parse和strftime将每个字符串组合成可以使用的日期。因此,对于“a”,我希望最终以“2014年9月19日、2014年9月20日、2014年9月25日、2014年9月26日、2014年10月2日等结束。然后我将使用strftime获取一周中的某一天(即2014年9月20日星期六等)。更新-在使用Cary提供的正则表达式一段时间后(谢谢!),当我在IRB中运行它时,我意识到它正在删除字符串中的最后一个日期。这是我运行的代码和输出。有人能告诉我为什么会发生这种情况吗?require'rubygems'require'nokogiri'require'open uri'str=“9月19日,20日,25日,26日,10月2日,3日,4日,10日,11月3日,12日,17日”dates=str.scan(/\D+(?:\D+,\s+/).map{|s |[s[/[a-z]+/I],s.scan(/\d+/)]}p日期输出如下。如您所见,十一月只返回2个日期,但字符串中有3个日期。它会删除十一月17日。[[“九月”,“十九”,“二十”,“二十五”,“二十六”],[“十月”,“二”,“三”,“四”,“十”],[”十一月,[ [ 3 ],“12”] ] C:\RaulsStAler-Ruy1.1.3\NokGoiRi>我解决了这个问题,但这样做决定改变我认为是一种改进的方法。
b.last.last << e
b.last.last << e.to_i