๐ WAYPOINT LESSON
CSV Parsing Rules
โญโญ intermediateโณ 14 min read๐ Lesson 87 of 180
RFC 4180's quoted fields and escaped quotes, and why split(',') is a bug โ plus the honest character scanner.
CSV: parsing rules that bite
Real CSV (RFC 4180) has three rules beginners miss:
- Quoted fields โ
"hello, world"is ONE field containing a comma. - Escaped quotes โ
""inside quotes is a literal". - Newlines in quotes โ a row can span lines.
A split(",") parser fails all three:
// naive โ breaks on quoted commas
String[] fields = line.split(",");
// character scanner โ the honest parser
List<String> parseRow(String line) {
List<String> out = new ArrayList<>();
StringBuilder cur = new StringBuilder();
boolean inQuotes = false;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (inQuotes) {
if (c == '"') {
if (i + 1 < line.length() && line.charAt(i + 1) == '"') { cur.append('"'); i++; }
else inQuotes = false;
} else cur.append(c);
} else if (c == '"') inQuotes = true;
else if (c == ',') { out.add(cur.toString()); cur.setLength(0); }
else cur.append(c);
}
out.add(cur.toString());
return out;
}
The scanner handles rules 1โ2; full rule 3 needs row-merging across lines โ beyond today's scope, but you now know why libraries exist.