问题描述
我正在尝试用 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
,
这是一种简单的非高尔夫方法:
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"
还有其他更惯用的方法,但这可以为您指明方向。