How can I split text on commas while keeping commas inside quoted phrases?
Quick answer
A plain comma split treats every comma as a separator, including commas inside quoted fields. For a tightly controlled string with double-quoted fields and no escaped quotes or embedded newlines, a regex can split only at commas followed by an even number of quotes. For actual CSV or input with varied quoting rules, use a CSV-aware parser configured for that format.
The question, the details, the next step.
A practical checklist
Decide whether the input is a simple, controlled string or CSV data with a defined dialect.
Use the regex only if quotes are balanced, unescaped, and the input is a single line.
For general CSV, choose a CSV-aware reader and configure its delimiter and quote character for the input.
Test representative cases, including a quoted comma and any escaping or line breaks the input may contain.
Inspect the parsed fields before using them if the input format is uncertain.
A few more useful answers
Will the regex remove the quotation marks?
No. The shown split leaves the quotation marks in the field. Removing them safely depends on the input rules; a CSV reader returns parsed field values for its configured dialect.
Does the regex handle doubled quotes inside a CSV field?
Not reliably. Its assumptions exclude escaped quotes, so use a CSV-aware parser for fields that may contain them.
Can a CSV field contain a newline?
Quoted fields can contain newlines under CSV conventions, and Python’s CSV reader supports records with quoted newlines. A one-line regex split is not a suitable general solution for that case. [S1]
Sources
References used for this guide.
- [S1] Python 3.12 documentation: CSV reader, delimiters, and quoting docs.python.org · Checked
- [S2] Python 3.16 documentation: regular-expression splitting docs.python.org · Checked
