Parse Quoted CSV Fields With A State Machine
Split a CSV line with a tiny state machine so quoted fields keep their commas and doubled quotes decode into literal quotation marks.
Code
import java.util.ArrayList;
import java.util.List;
public class CsvLine {
// tiny state machine (RFC 4180): quoted fields may contain commas and ""
static List<String> parseLine(String line) {
List<String> fields = new ArrayList<>();
StringBuilder current = 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) == '"') {
current.append('"'); // 成对引号 -> 字面引号
i++;
} else {
inQuotes = false; // 收尾引号
}
} else {
current.append(c);
}
} else if (c == '"') {
inQuotes = true;
} else if (c == ',') {
fields.add(current.toString());
current.setLength(0);
} else {
current.append(c);
}
}
fields.add(current.toString());
return fields;
}
public static void main(String[] args) {
String line = "\"Smith, John\",42,\"said \"\"hi\"\"\"";
List<String> fields = parseLine(line);
System.out.println("fields = " + fields.size());
fields.forEach(f -> System.out.println("- " + f));
}
}What the code does
All of the logic lives in the class CsvLine and the functions parseLine and main.
The one repetition in this snippet is the loop for (int i = 0; i < line.length(); i++).
Watch out for
- The project gains no new entries before this can run.
Using it
Signature: static List<String> parseLine(String line)
Running the file prints labeled results such as fields = — each operation’s effect is visible in the output.
There are 1 call inside main — parseLine — executed top to bottom.
Key statements
String line = "\"Smith, John\",42,\"said \"\"hi\"\"\"";
StringBuilder current = new StringBuilder();
List<String> fields = new ArrayList<>();
Interactive Tools for This Topic
CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.CSV to Markdown TableConvert CSV data, including quoted fields with embedded commas and newlines, into a clean GitHub-flavored Markdown table with selectable alignment.CSV to TSV ConverterParse RFC 4180 CSV with quoted fields and re-serialize using a tab, pipe, semicolon, or custom delimiter, with optional quoting.
FAQ
- What does Parse Quoted CSV Fields With A State Machine print when run?
- The script runs standalone; its 1 labeled outputs include `fields =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.