Parsing Comma-Separated Values

While we have already seen a basic CSV grammar in ​Pattern: Sequence​, let’s beef it up with the notion of a header row and allow empty columns. Here’s a representative input file:

​ Details,Month,Amount
​ Mid Bonus,June,"$2,000"
​ ,January,"""zippo"""
​ Total Bonuses,"","$5,000"

Header rows are no different from regular rows; we simply interpret the column value as the column header name. Rather than using a row+ ANTLR fragment to match rows as well as the header row, we match it separately. When building a real application based upon this grammar, we’d probably want to treat the header differently. This way, we can get a handle on the first special row. Here’s the first ...

Get The Definitive ANTLR 4 Reference, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.