我试图用ruby解析一个多行固定宽度的文件,但似乎无法解析我需要的信息。当信息在一行中时,我可以很好地解析。例如:
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值。
这里有一个简单的、非golfed的方法:
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"
还有其他更惯用的方法,但这会给你一个方向的提示。
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演示。