字符串到数组和哈希与正则表达式

时间:2010-02-02 07:32:23

标签: ruby-on-rails ruby regex

我想像开场时间一样打开一个字符串:

"Monday-Friday>10:00-18:00;Saturday>12:00-17:00;Sunday>12:00-15:00"

进入这个:

[ {:period => "Monday-Friday", :hours => "10:00-18:00"}, {:period => "Saturday", :hours => "12:00-17:00"}, {:period => "Sunday", :hours => "12:00-15:00"} ]

我正在尝试使用String.scan()方法,但无法弄清楚Regexp。

此外,如果您有任何反向建议,请以最佳方式(即从表格获取开放时间时)。

更新 - 谢谢大家找到完美的解决方案!现在我正在使用(感谢kejadlen):

str.scan(/([\w-]+)>([\d:-]+)-([\d:]+)/).map { |(p,o,c)| {:period => p, :opens => o, :closes => c} }

但现在如何扭转它=)所以给出:

[ {:opens=>"10:00", :closes=>"18:00", :period=>"Monday-Friday"}, 
  {:opens=>"12:00", :closes=>"17:00", :period=>"Saturday"}, 
  {:opens=>"12:00", :closes=>"15:00", :period=>"Sunday"} ]

我想把它合并到:

"Monday-Friday>10:00-18:00;Saturday>12:00-17:00;Sunday>12:00-15:00"

5 个答案:

答案 0 :(得分:3)

如果您更喜欢单行:

s = "Monday-Friday>10:00-18:00;Saturday>12:00-17:00;Sunday>12:00-15:00"
s.split(/;/).map{|i| Hash[[[:period, :hours], i.split(/>/)].transpose]}
# or
s.split(/;/).map{|i| p, h = i.split(/>/); {:period => p, :hours => h}}
#=> [{:period=>"Monday-Friday", :hours=>"10:00-18:00"}, {:period=>"Saturday", :hours=>"12:00-17:00"}, {:period=>"Sunday", :hours=>"12:00-15:00"}]

编辑:

反过来说,这应该做的工作:

a.map{|i| "#{i[:period]}>#{i[:opens]}-#{i[:closes]}"}.join(';')
=> "Monday-Friday>10:00-18:00;Saturday>12:00-17:00;Sunday>12:00-15:00"

答案 1 :(得分:2)

这就是我要做的事情

str="Monday-Friday>10:00-18:00;Saturday>12:00-17:00;Sunday>12:00-15:00"
periods = str.split(';') 
#=> ["Monday-Friday>10:00-18:00", "Saturday>12:00-17:00", "Sunday>12:00-15:00"]
period_array=[]
periods.each do |period| 
  period_with_hours = period.split('>')
  period_array << {:period =>  period_with_hours.first, :hours => period_with_hours.last}
end

period_array

#=> [{:period=>"Monday-Friday", :hours=>"10:00-18:00"}, {:period=>"Saturday", :hours=>"12:00-17:00"}, {:period=>"Sunday", :hours=>"12:00-15:00"}]

答案 2 :(得分:0)

试试这个:

String S =  ([^\>]*)\>([^\;]*)\;
String T = " {:period => $1, :hours => $2}, "
originalString.replaceAll(S,T);

可能需要更多地使用正则表达式,但是应该这样做。

编辑 - 嗯,您在ruby的上下文中询问了答案,我给了您Java答案,但正则表达式应该仍然有效......

答案 3 :(得分:0)

这看起来很有效

the_input.split(';').collect{|pair|
    period, hours = pair.split('>')
    {:period => period, :hours => hours}
}
=> [{:hours=>"10:00-18:00", :period=>"Monday-Friday"}, {:hours=>"12:00-17:00", :
period=>"Saturday"}, {:hours=>"12:00-15:00", :period=>"Sunday"}]

答案 4 :(得分:0)

str.scan(/([\w-]+)>([\d:-]+)/).map {|(p,h)| {:period => p, :hours => h }}