java csv逗号转义_如何使用Javascript解析包含数据逗号的CSV字符串?

免责声明

2014-12-01更新:下面的答案只适用于CSV的一种非常具体的格式。正如DG在评论中正确指出的那样,该解决方案不符合RFC 4180对CSV的定义,也不符合MSExcel格式。这个解决方案简单地演示了如何解析一个(非标准的)CSV输入行,其中包含字符串类型的混合,其中字符串可能包含转义引号和逗号。

一种非标准的CSV解决方案

正如austincheney正确指出的那样,如果您想正确地处理可能包含转义字符的引用字符串,那么确实需要从头到尾解析字符串。此外,OP没有明确定义“CSV字符串”的真正含义。首先,我们必须定义什么构成有效的CSV字符串及其单独的值。

给定:“CSV字符串”定义

为了本讨论的目的,“CSV字符串”由零或多个值组成,其中多个值用逗号分隔。每项价值可包括:双引号双引号(可能包含未转义的单引号。)

单引号引号(可能包含未转义的双引号。)

没有引号的字符串。(可能不包含引号、逗号或反斜杠。)

一个空值。(All空格值被认为是空的。)

规则/说明:引用的值可能包含逗号。

引用的值可能包含转义-任何,例如。

'that\'s cool'.

必须引用包含引号、逗号或反斜杠的值。

必须引用包含前导或尾随空格的值。

反斜杠从所有对象中移除:

\'以单引号为单位。

反斜杠从所有对象中移除:

\"以双引号表示。

没有引号的字符串被裁剪为任何前导和尾随空格。

逗号分隔符可能有相邻的空格(被忽略)。

查找:

JavaScript函数,它将有效的CSV字符串(如上所述)转换为字符串值数组。

解决办法:

此解决方案使用的正则表达式是复杂的。和(国际水文学组织)全非平凡的正则表达式应该在自由间距模式下显示,并有大量的注释和缩进。不幸的是,JavaScript不允许自由间隔模式.因此,该解决方案实现的正则表达式首先以本机regex语法(使用Python的Handy)表示:r'''...'''(原始-多行字符串语法)。

首先是一个正则表达式,它验证CVS字符串是否满足上述要求:

验证“CSV字符串”的Regex: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.

"""

如果一个字符串与上面的regex匹配,那么该字符串就是一个有效的CSV字符串(根据前面提到的规则),并且可以使用下面的regex进行解析。然后使用下面的regex来匹配CSV字符串中的一个值。它被反复应用,直到找不到更多的匹配(并且所有的值都被解析了)。

解析有效CSV字符串中的一个值的Regex: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.

"""

请注意,有一个特例值是这个正则表达式不匹配的-该值为空时的最后一个值。这个特别“空最后值”CASE由以下js函数进行测试和处理。

JavaScript函数解析CSV字符串:// 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 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"

这实际上并不是一个限制,因为任何子字符串都可以表示为单个或双引号值。还请注意,此解决方案仅代表一个可能的定义:“逗号分隔的值”。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值