LoginSignup
18
19

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-03-15

実装

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

18
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
19