我有以下类型的字符串
var string = "'string, duppi, du', 23, lala"
我想将字符串拆分为每个逗号上的数组,但只有单引号外的逗号。我无法找出拆分的正确正则表达式...
string.split(/,/)
会给我["'string", " duppi", " du'", " 23", " lala"]
但结果应该是:["string, duppi, du", "23", "lala"]
有跨浏览器的解决方案吗?
最佳答案
免责声明
2014-12-01 更新:以下答案仅适用于一种非常特定的 CSV 格式。正如正确指出的by DG in the comments ,此解决方案不符合 CSV 的 RFC 4180 定义,也不符合 Microsoft Excel 格式。该解决方案简单地演示了如何解析包含混合字符串类型的一个(非标准)CSV 输入行,其中字符串可能包含转义引号和逗号。
一个非标准的CSV解决方案
如 austincheney correctly points out ,如果您希望正确处理可能包含转义字符的带引号的字符串,您确实需要从头到尾解析字符串。此外,OP 没有明确定义“CSV 字符串”到底是什么。首先,我们必须定义什么构成有效的 CSV 字符串及其各个值。
给定:“CSV 字符串”定义
出于本次讨论的目的,“CSV 字符串”由零个或多个值组成,其中多个值用逗号分隔。每个值可能包括:
规则/注意事项:
'that\'s cool'
. \'
在单引号中。 \"
在双引号中。 查找:
将有效的 CSV 字符串(如上定义)转换为字符串值数组的 JavaScript 函数。
解决方法:
此解决方案使用的正则表达式很复杂。并且(恕我直言)所有非平凡的正则表达式都应该以自由间距模式呈现,并带有大量注释和缩进。不幸的是,JavaScript 不允许自由间距模式。因此,此解决方案实现的正则表达式首先以 native 正则表达式语法呈现(使用 Python 方便的
r'''...'''
原始多行字符串语法表示)。首先是一个正则表达式,用于验证 CVS 字符串是否满足上述要求:
验证“CSV 字符串”的正则表达式:
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 字符串中的一个值。它会重复应用,直到找不到更多匹配项(并且所有值都已解析)。从有效的 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.
"""
请注意,此正则表达式不匹配一个特殊情况值 - 当该值为空时的最后一个值。这种特殊的“最后一个值为空”的情况由后面的 JavaScript 函数测试和处理。解析 CSV 字符串的 JavaScript 函数:
// 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}
. (这是为了帮助可视化前导/尾随空格和零长度字符串。)// Test 1: Test string from original question.
var test = "'string, duppi, du', 23, lala";
var a = CSVtoArray(test);
/* Array has three elements:
a[0] = {string, duppi, du}
a[1] = {23}
a[2] = {lala} */
// Test 2: Empty CSV string.
var test = "";
var a = CSVtoArray(test);
/* Array has zero elements: */
// Test 3: CSV string with two empty values.
var test = ",";
var a = CSVtoArray(test);
/* Array has two 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 has three 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 has three 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 has eight 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"
这并不是真正的限制,因为任何子字符串都可以表示为单引号或双引号值。另请注意,此解决方案仅表示“逗号分隔值”的一种可能定义。编辑历史
关于javascript - 如何使用 JavaScript 解析数据中包含逗号的 CSV 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8493195/