将自定义日志文件解析为哈希数组

bee*_*ees 2 ruby parsing

我想解析一个有3个条目的日志文件.它看起来像这样:

Start: foo
Parameters: foo
End: foo

Start: other foo
Parameters: other foo
End: other foo

....
Run Code Online (Sandbox Code Playgroud)

foo就是我想要的.如果结果如下所示会很好:

logs = [
{
  :start=>"foo",
  :parameters=>"foo",
  :end=>"foo"
},
{
  :start=>"other foo",
  :parameters=>"other foo",
  :end=>"other foo"
}
]
Run Code Online (Sandbox Code Playgroud)

我知道一些正则表达式,但是我很难理解我如何通过多行来解决这个问题.谢谢!

cam*_*cam 5

执行此操作的最佳方法是使用多行正则表达式:

logs = file.scan /^Start: (.*)\nParameters: (.*)$\nEnd: (.*)$/
#  => [["foo", "foo", "foo"], ["other foo", "other foo", "other foo"]]
logs.map! { |s,p,e|  { :start => s, :parameters => p, :end => e } }
#  => [ {:start => "foo", :parameters => "foo", :end => "foo" }, ... ]
Run Code Online (Sandbox Code Playgroud)