2 Ağustos 2007 Perşembe

Parse Windows .ini Format

#thanks to gdsx in #ruby-lang
def tame(input)
tamed = {}

# split data on city names, throwing out surrounding brackets
input = input.split(/\[([^\]]+)\]/)[1..-1]

# sort the data into key/value pairs
input.inject([]) {|tary, field|
tary << field
if(tary.length == 2)
# we have a key and value; put 'em to use
tamed[tary[0]] = tary[1].sub(/^\s+/,'').sub(/\s+$/,'')
# pass along a fresh temp-array
tary.clear
end
tary
}

tamed.dup.each { |tkey, tval|
tvlist = tval.split(/[\r\n]+/)
p tvlist
tamed[tkey] = tvlist.inject({}) { |hash, val|
k, v = val.split(/=/)
hash[k]=v
hash
}
}

tamed
end


# here's what the input looks like

[Amsterdam]
Address=Amstelveenseweg 438;1084 JH;Amsterdam

[Antwerp]
Address=Uitbreidingstraat 4;4-600;Antwerp

[Austin]
Address=4221 South Harbor Expressway, Suite 400;Austin, Texas 78746

[Baltimore / Smith]
City=Baltimore
Address=225 Johnson Avenue;Baltimore, Maryland 21209-3600

[Baltimore / Calvert]
City=Baltimore
Address=151 South Belmont Street, Suite 2350;Baltimore, Maryland 21202-6832

[Bangkok]
Address=Unit 543, London Tower;495 North Sathorn Road, Yannawa, Sathorn Bangkok 45467
Country=Thailand

[Bergen]
Country=Norway
City=Bergen
Address=Torgallmenningen 4B;PO Box 2153 Sentrum, N-5811;Bergen



# here's the output

{"Bergen"=>{"City"=>"Bergen", "Country"=>"Norway", "Address"=>"Torgallmenningen 4B;PO Box 2153 Sentrum, N-5811;Bergen"}, "Antwerp"=>{"Address"=>"Uitbreidingstraat 4;4-600;Antwerp"}, "Baltimore / Smith"=>{"City"=>"Baltimore", "Address"=>"225 Johnson Avenue;Baltimore, Maryland 21209-3600"}, "Amsterdam"=>{"Address"=>"Amstelveenseweg 438;1084 JH;Amsterdam"}, "Bangkok"=>{"Country"=>"Thailand", "Address"=>"Unit 543, London Tower;495 North Sathorn Road, Yannawa, Sathorn Bangkok 45467"}, "Austin"=>{"Address"=>"4221 South Harbor Expressway, Suite 400;Austin, Texas 78746"}, "Baltimore / Calvert"=>{"City"=>"Baltimore", "Address"=>"151 South Belmont Street, Suite 2350;Baltimore, Maryland 21202-6832"}


0 Comments: