Edited at

HaskellでParsecを使ってCSVをパースする

More than 3 years have passed since last update.


実装

import Text.Parsec

csvStruct = endBy line eol
line = sepBy cell $ char ','
cell = many $ noneOf ",\n"
eol = char '\n'

parseCSV :: String -> Either ParseError [[String]]
parseCSV src = parse csvStruct "* ParseError *" src


実行結果

% ghci ParseCSV.hs

*Main> parseCSV "aa,bb,cc\n"
Right [["aa","bb","cc"]]

*Main> parseCSV "a,b,c\nd,e,x\n"
Right [["a","b","c"],["d","e","x"]]

*Main> parseCSV "invalid,a,b"
Left "* ParseError *" (line 1, column 12):
unexpected end of input
expecting "," or "\n"

*Main> parseCSV "valid\n"
Right [["valid"]]


結論

Haskell/Text.Parsecは美しい。

正規表現に疲れた方にはおすすめ。