Help us understand the problem. What is going on with this article?

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は美しい。
正規表現に疲れた方にはおすすめ。

tadokoro
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away