Comma Separated Values

Problem

You want to work with comma separated value records, such as those exported from popular spreadsheet and database programs. Note that this recipe works for any similarly delimited format.

Solution

The naive implementation might be something like this:

1> string:tokens(csv-string, ",").

The shortcomings show up pretty quickly. For starters, CSV format often encloses fields in quotes, so fields can contain commas. On top of that, quoted fields can contain quotes, escaped with a backslash (#\\). Let's imagine a CSV format for books, where the format is author,title,ISBN,publisher:

2> Csv = "David Halberstam, \"War in a Time of Peace: Bush, Clinton,
2> and the Generals\", B0000C37EA, Scribner".
"David Halberstam, \"War in a Time of Peace: Bush, Clinton, and the
Generals\", B0000C37EA, Scribner".
3> string:tokens(Csv, ",").
["David Halberstam",
" \"War in a Time of Peace: Bush",
" Clinton",
" and the Generals\"",
" B0000C37EA",
" Scribner"]

Clearly, the easy solution won't work for the general case. Essentially, we need to do state machine processing for this. As we traverse the string, we'll encounter the following states: in_field (when the current position is inside a field), in_quote (when we're inside a quoted string), delim (when we encounter a delimiter), and escape_char (when we encounter a backslash).

A set of Scheme utilities (written by NeilVanDyke) handles this problem quite nicely, but is obviously not applicable to Erlang directly. This is a good idea for an Erlang library, and could be ported to Erlang relatively easily.