我有以下类型的字符串
var string = "'string, duppi, du', 23, lala"
我想将字符串拆分为每个逗号的数组,但仅将单引号之外的逗号分隔。
我想不出正确的正则表达式进行拆分…
string.split(/,/)
会给我
["'string", " duppi", " du'", " 23", " lala"]
但结果应该是:
["string, duppi, du", "23", "lala"]
有什么跨浏览器解决方案?
以下答案仅适用于一种非常特定的CSV格式。正如DG在评论中正确指出的那样,此解决方案不适合RFC 4180定义的CSV,也不适合MSExcel格式。此解决方案仅演示了如何解析一个(非标准)CSV输入行,其中包含混合的字符串类型,其中的字符串可能包含转义的引号和逗号。
正如austincheney正确指出的那样,如果您希望正确处理可能包含转义字符的带引号的字符串,则确实需要从头到尾解析该字符串。另外,OP并未明确定义“CSV字符串”的真正含义。首先,我们必须定义什么构成有效的CSV字符串及其各个值。
为了便于讨论,“ CSV字符串”由零个或多个值组成,其中多个值之间用逗号分隔。每个值可以包括:
规则/说明:
'that\'s cool'
\'
\"
一个JavaScript函数,可将有效的CSV字符串(如上定义)转换为字符串值的数组。
该解决方案使用的正则表达式很复杂。并且(IMHO)所有非平凡的正则表达式都应以自由行距模式呈现,并带有大量注释和缩进。不幸的是,JavaScript不允许使用自由间距模式。因此,此解决方案实现的正则表达式首先以本机regex语法表示(使用Python的方便:r'''...'''raw-multi-line-string语法表示)。
r'''...'''
首先,这里是一个正则表达式,它验证CVS字符串是否满足上述要求:
re_valid = r""" # Validate a CSV string having single, double or un-quoted values. ^ # Anchor to start of string. \s* # Allow whitespace before value. (?: # Group for value alternatives. '[^'\\]*(?:\\[\S\s][^'\\]*)*' # Either Single quoted string, | "[^"\\]*(?:\\[\S\s][^"\\]*)*" # or Double quoted string, | [^,'"\s\\]*(?:\s+[^,'"\s\\]+)* # or Non-comma, non-quote stuff. ) # End group of value alternatives. \s* # Allow whitespace after value. (?: # Zero or more additional values , # Values separated by a comma. \s* # Allow whitespace before value. (?: # Group for value alternatives. '[^'\\]*(?:\\[\S\s][^'\\]*)*' # Either Single quoted string, | "[^"\\]*(?:\\[\S\s][^"\\]*)*" # or Double quoted string, | [^,'"\s\\]*(?:\s+[^,'"\s\\]+)* # or Non-comma, non-quote stuff. ) # End group of value alternatives. \s* # Allow whitespace after value. )* # Zero or more additional values $ # Anchor to end of string. """
如果一个字符串与上述正则表达式匹配,则该字符串是有效的CSV字符串(根据前面所述的规则),并且可以使用以下正则表达式进行解析。然后,以下正则表达式用于匹配CSV字符串中的一个值。重复应用它,直到找不到更多匹配项(并且所有值都已解析)。
re_value = r""" # Match one value in valid CSV string. (?!\s*$) # Don't match empty last value. \s* # Strip whitespace before value. (?: # Group for value alternatives. '([^'\\]*(?:\\[\S\s][^'\\]*)*)' # Either $1: Single quoted string, | "([^"\\]*(?:\\[\S\s][^"\\]*)*)" # or $2: Double quoted string, | ([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*) # or $3: Non-comma, non-quote stuff. ) # End group of value alternatives. \s* # Strip whitespace after value. (?:,|$) # Field ends on comma or EOS. """
请注意,此正则表达式有一个不匹配的特殊情况值-当该值为空时的最后一个值。这种特殊的 “空的最后一个值” 案例将通过以下js函数进行测试和处理。
// Return array of string values, or NULL if CSV string not well formed. function CSVtoArray(text) { var re_valid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/; var re_value = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g; // Return NULL if input string is not well formed CSV string. if (!re_valid.test(text)) return null; var a = []; // Initialize array to receive values. text.replace(re_value, // "Walk" the string using replace with callback. function(m0, m1, m2, m3) { // Remove backslash from \' in single quoted values. if (m1 !== undefined) a.push(m1.replace(/\\'/g, "'")); // Remove backslash from \" in double quoted values. else if (m2 !== undefined) a.push(m2.replace(/\\"/g, '"')); else if (m3 !== undefined) a.push(m3); return ''; // Return empty string. }); // Handle special case of empty last value. if (/,\s*$/.test(text)) a.push(''); return a; };
在以下示例中,花括号用于定界{result strings}。(这有助于可视化前导/尾随空格和零长度字符串。)
{result strings}
// Test 1: Test string from original question. var test = "'string, duppi, du', 23, lala"; var a = CSVtoArray(test); /* Array hes 3 elements: a[0] = {string, duppi, du} a[1] = {23} a[2] = {lala} */ // Test 2: Empty CSV string. var test = ""; var a = CSVtoArray(test); /* Array hes 0 elements: */ // Test 3: CSV string with two empty values. var test = ","; var a = CSVtoArray(test); /* Array hes 2 elements: a[0] = {} a[1] = {} */ // Test 4: Double quoted CSV string having single quoted values. var test = "'one','two with escaped \' single quote', 'three, with, commas'"; var a = CSVtoArray(test); /* Array hes 3 elements: a[0] = {one} a[1] = {two with escaped ' single quote} a[2] = {three, with, commas} */ // Test 5: Single quoted CSV string having double quoted values. var test = '"one","two with escaped \" double quote", "three, with, commas"'; var a = CSVtoArray(test); /* Array hes 3 elements: a[0] = {one} a[1] = {two with escaped " double quote} a[2] = {three, with, commas} */ // Test 6: CSV string with whitespace in and around empty and non-empty values. var test = " one , 'two' , , ' four' ,, 'six ', ' seven ' , "; var a = CSVtoArray(test); /* Array hes 8 elements: a[0] = {one} a[1] = {two} a[2] = {} a[3] = { four} a[4] = {} a[5] = {six } a[6] = { seven } a[7] = {} */
此解决方案要求CSV字符串为“有效”。例如,未加引号的值不能包含反斜杠或引号,例如,以下CSV字符串无效:
var invalid1 = "one, that's me!, escaped \, comma"
这并不是真正的限制,因为任何子字符串都可以表示为单引号或双引号。还请注意,此解决方案仅代表以下一种可能的定义:“逗号分隔值”。