Comment detail

RFC 4180対応版 CSVレコードの分解 (Nested Flatten)
あえて自力でやってみました。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def parse_csv(d)
	records = []
	columns = []
	buffer = ""
	in_quote = false

	i = 0
	while i < d.size
		if d[i] == ?"
			if d[i+1] != ?"
				in_quote = !in_quote
				i += 1
				next
			else
				i += 1
			end
		end
		
		unless in_quote
			if d[i] == ?, || d[i] == ?\n
				columns << buffer
				buffer = ""

				if d[i] == ?\n
					records << columns
					columns = []
				end
				i += 1
				next
			end
		end

		buffer += d[i].chr
		i += 1
	end

	records
end

data=<<EOT
"aaa","b
bb","ccc",zzz,"y""Y""y",xxx
EOT

records=parse_csv(data)
records.first.each_with_index{ |r,index|
	puts "#{index+1} => #{r}"
}

Index

Feed

Other

Link

Pathtraq

loading...