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.

JavaData Integrity

Code

snippet
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

FAQ

What does Parse Quoted CSV Fields With A State Machine print when run?
The script runs standalone; its 1 labeled outputs include `fields =`.