From: Massimiliano Mirra Date: 2002-02-14T06:29:13+09:00 Subject: Re: (CSV) text file processing... On Thu, Feb 14, 2002 at 01:34:37AM +0900, Bob wrote: > Any such examples out there? The following csv_split comes from ruby-talk archives. I adapted it a bit allow for a different than the comma. Tests shows examples of usage. Massimiliano class String def csv_split(div = ',') scan(/(?:\A|#{div})\s*"([^"]*)"|(?:\A|#{div})([^"#{div}]*)(?=#{div}|\z)/).flatten.compact end end if $0 == __FILE__ require 'Lapidary/TestCase' module Test class CSVSplit < Lapidary::TestCase def testStringWithCommas s = 'a,b,c' assert_equal ['a', 'b', 'c'], s.csv_split end def testStringWithCommasAndQuotes s = 'a,"b,c",d' assert_equal ['a', 'b,c', 'd'], s.csv_split end def testStringWithColons s = 'a;b;c;"d;e"' assert_equal ['a', 'b', 'c', 'd;e'], s.csv_split(';') end def testStringWithTabs s = "a\tb\t\"c\td\"\te" assert_equal ['a','b',"c\td", 'e'], s.csv_split("\t") end end class All def All.suite suite = Lapidary::TestSuite.new suite.add(CSVSplit.suite) suite end end end require 'Lapidary/UI/Console/TestRunner' Lapidary::UI::Console::TestRunner.run(Test::All) end