在 JavaScript 中试试这个
(?:(?:[^,"'\n]*(?:(?:"[^"\n]*")|(?:'[^'\n]*'))[^,"'\n]*)+)|[^,\n]+
Demo
添加组以提高可读性(删除 ?name> for Javascript)
(?<has_quotes>(?:[^,"'\n]*(?:(?<double_quotes>"[^"\n]*")|(?<single_quotes>'[^'\n]*'))[^,"'\n]*)+)|(?<simple>[^,\n]+)
Demo
解释:
(?<double_quotes>"[^"\n]*") 匹配 "Any inside 但不是 "" = (1)(双引号)
(?<single_quotes>'[^'\n]*') 匹配 'Any inside 但不是 '@ 987654330@ = (2)(单引号)
(?:(?<double_quotes>"[^"\n]*")|(?<single_quotes>'[^'\n]*')) 匹配 (1)or(2) = (3)
[^,"'\n]* 匹配任何文本,但不是 "', = (w)
(?:(?:(?<double_quotes>"[^"\n]*")|(?<single_quotes>'[^'\n]*'))[^,"'\n]*) 匹配 (3)(w)
(?:(?:(?<double_quotes>"[^"\n]*")|(?<single_quotes>'[^'\n]*'))[^,"'\n]*)+ 匹配重复 (3)(w) = ( 3w+)
(?<has_quotes>[^,"'\n]*(?:(?:(?<double_quotes>"[^"\n]*")|(?<single_quotes>'[^'\n]*'))[^,"'\n]*)+) 匹配 (w)(3w+) = (4)(带引号)
[^,\n]+ 匹配其他情况 (5)(简单)
所以在最后我们有 (4)|(5) (有引号或简单)
输入
abcd,efgh, ijkl
abcd, efgh, ij"k,l", mnop, 'q,rs't
'q, rs't
"'q,rs't, ij"k, l""
输出:
MATCH 1
simple [0-4] `abcd`
MATCH 2
simple [5-9] `efgh`
MATCH 3
simple [10-15] ` ijkl`
MATCH 4
simple [16-20] `abcd`
MATCH 5
simple [21-26] ` efgh`
MATCH 6
has_quotes [27-35] ` ij"k,l"`
double_quotes [30-35] `"k,l"`
MATCH 7
simple [36-41] ` mnop`
MATCH 8
has_quotes [42-50] ` 'q,rs't`
single_quotes [43-49] `'q,rs'`
MATCH 9
has_quotes [51-59] `'q, rs't`
single_quotes [51-58] `'q, rs'`
MATCH 10
has_quotes [60-74] `"'q,rs't, ij"k`
double_quotes [60-73] `"'q,rs't, ij"`
MATCH 11
has_quotes [75-79] ` l""`
double_quotes [77-79] `""`