解析 ruby 中的多行固定宽度文本文件

Parse multiline fixed-width text files in ruby

我正在尝试解析 ruby 中的多行固定宽度文件,但似乎无法解析我需要的信息。当信息在 1 行时,我可以很好地解析。例如:

Name      LastName         DOB
John      Doe              01/01/2001
Jane      Doe              01/02/2002

但我面临的挑战是当文件确实具有如下结构时

This message needs to be                 AccountId: 7854639
parsed in a single key                   Phone: 823972839563
of the json that I want to produce       Email: test@test.com

多行文字总比方说在同一个坐标上,而且是动态的。例如,不确定如何解析它并映射到 json 值。

str = "This message needs to be          AccountId: 7854639
parsed in a single key                   Phone: 823972839563
of the json that I want to produce       Email: test@test.com"

p str.scan(/([^\s]+:[^\n]+)/).flatten

参见Ruby demo

这里有一个简单的、没有难度的方法:

freeform_text = str.split('\n').map do |s|
  m = s.match(/^(.*)\s+(.*):(.*)$/)
  m[1] ? m[1].strip : ''
end.join(' ')

# Produces:
# "This message needs to be parsed in a single key of the json that I want to produce"

还有其他更惯用的方法,但这为您指明了方向。