Regex to Match CSV Fields
Match individual CSV fields handling both quoted and unquoted values. Supports escaped double quotes within quoted fields. Free online regex tester.
Regular Expression
/(?:"([^"]*(?:""[^"]*)*)"|([^",\n]*))/g
Token Breakdown
| Token | Description |
|---|---|
| (?: | Start of non-capturing group |
| " | Matches the literal character '"' |
| ( | Start of capturing group |
| [^"] | Negated character class — matches any character NOT in " |
| * | Matches the preceding element zero or more times (greedy) |
| (?: | Start of non-capturing group |
| " | Matches the literal character '"' |
| " | Matches the literal character '"' |
| [^"] | Negated character class — matches any character NOT in " |
| * | Matches the preceding element zero or more times (greedy) |
| ) | End of group |
| * | Matches the preceding element zero or more times (greedy) |
| ) | End of group |
| " | Matches the literal character '"' |
| | | Alternation — matches the expression before OR after the pipe |
| ( | Start of capturing group |
| [^",\n] | Negated character class — matches any character NOT in ",\n |
| * | Matches the preceding element zero or more times (greedy) |
| ) | End of group |
| ) | End of group |
Detailed Explanation
This regex matches individual fields in CSV (Comma-Separated Values) data, handling both quoted and unquoted values according to RFC 4180. Here is the token-by-token breakdown:
(?: — Opens a non-capturing group for the two field type alternatives.
" — Matches the opening double quote of a quoted field.
([^"](?:""[^"])) — Capturing group 1 matches the content of a quoted field. [^"] matches zero or more non-quote characters. The inner non-capturing group (?:""[^"]) handles escaped double quotes: "" represents a literal quote within the field, followed by more non-quote characters. This can repeat zero or more times.
" — Matches the closing double quote of the quoted field.
| — Alternation operator separating quoted and unquoted alternatives.
([^",\n]*) — Capturing group 2 matches an unquoted field. It captures zero or more characters that are not double quotes, commas, or newlines. These are the characters that can appear in a simple unquoted CSV field.
) — Closes the non-capturing group.
The g flag enables global matching to find all fields in a CSV line. This pattern correctly handles fields containing commas when they are quoted, fields containing escaped double quotes, empty fields, and simple unquoted fields. It is useful for CSV parsing, data import tools, and spreadsheet processing applications.
Example Test Strings
| Input | Expected |
|---|---|
| simple | Match |
| "quoted field" | Match |
| "field with ""quotes""" | Match |
| "has, comma" | Match |
| Match |
Try It — Interactive Tester
Match Highlighting(9 matches)
Matches & Capture Groups
36 charsFlags: gMatches: 9Ctrl+Shift+C to copy regex