Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Start of string |
(( |
Start of a capturing group (group 1) | Start of group 1 |
([^,"\r\n]+) |
Capturing group (group 2) for unquoted fields: one or more characters that are not commas, quotes, or newlines (\r or \n) | abc, 123, xyz |
) |
End of capturing group 2 | End of unquoted field |
| |
Alternation: OR operator between unquoted and quoted field patterns | Separates two alternatives |
("([^"]|"")*") |
Capturing group (group 3) for quoted fields: a double quote, followed by zero or more occurrences of either a non-quote character or two consecutive quotes (escaped quote), followed by a closing double quote | "hello", "it""s me" |
) |
End of capturing group 1 (outer group for field) | End of field definition |
( |
Start of a non-capturing group for the comma-separated list | Start of repetition group |
, |
Literal comma: separates fields in the list | , |
(([^,"\r\n]+)|("([^"]|"")*")) |
Capturing group (group 4) for subsequent fields: identical to the first field pattern (unquoted or quoted) | Same as first field |
) |
End of non-capturing group for repetition | End of repetition unit |
* |
Quantifier: zero or more occurrences of the preceding group (comma + field) | Repeats the field separator |
$ |
Anchor: asserts position at end of the string | End of string |
Matches
abc,123,xyz"hello","world"a,"b,c",d"it""s","a,test"single"quoted"
Does not match
abc,"defabc,def"abc,"def"ghiabc,defabc,"def""abc,,def,abc
Common pitfalls
- Unescaped quotes inside quoted fields (e.g., "abc"def" will not match).
- Newlines within fields (e.g., abc def will not match).
- Trailing commas (e.g., abc, will not match).
- Leading commas (e.g., ,abc will not match).
- Unquoted fields containing commas (e.g., abc,def will not match as a single field).
Performance notes
The pattern is prone to catastrophic backtracking if the input contains many consecutive commas or malformed quoted strings. The alternation and nested quantifiers can lead to exponential time complexity in worst-case scenarios. Anchoring (^ and $) ensures the entire string is validated, which is efficient for well-formed inputs.