Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | |
( |
Start of a non-capturing group (outer alternation) | |
[^,"\r\n]+ |
Character class: one or more characters that are not comma, quote, carriage return, or newline | abc,123,field |
| |
Alternation: matches either the left or right side of the group | |
" |
Literal double quote: starts a quoted field | " |
([^"]|"")* |
Group: zero or more occurrences of either a non-quote character or an escaped quote ("") | text""more |
" |
Literal double quote: ends a quoted field | " |
) |
End of the outer alternation group | |
(,\s*([^,"\r\n]+|"([^"]|"")*"))* |
Group: zero or more occurrences of a comma, optional whitespace, and a field (same pattern as first field) | , field1, "quoted" |
$ |
Anchor: asserts position at end of the string | |
Matches
abc,123,"quoted,field""escaped""quote",field2simplea,"b",cfield1, field2, "field,3"
Does not match
abc,abc,"unterminatedabc,"field""abc, fieldabc,"fieldfield,a,"b",c,
Common pitfalls
- Failing to escape quotes inside quoted fields (e.g., using " instead of "")
- Assuming trailing commas are allowed (they are not in this pattern)
- Ignoring whitespace after commas (pattern allows optional whitespace)
- Not accounting for escaped quotes in quoted fields (e.g., "" is valid, " is not)
Performance notes
The pattern has nested quantifiers (*) which can lead to catastrophic backtracking for malformed input (e.g., long sequences of quotes). Anchors (^ and $) are correctly placed to prevent partial matches. Consider simplifying or using possessive quantifiers if performance is critical.