如何使用Javascript解析CSV字符串,其中包含数据中的逗号?

Han*_*ans 79 javascript regex split

我有以下类型的字符串

var string = "'string, duppi, du', 23, lala"
Run Code Online (Sandbox Code Playgroud)

我想将字符串拆分为每个逗号上的数组,但只有单引号外的逗号.

我无法弄清楚分裂的正确正则表达式......

string.split(/,/)
Run Code Online (Sandbox Code Playgroud)

会给我的

["'string", " duppi", " du'", " 23", " lala"]
Run Code Online (Sandbox Code Playgroud)

但结果应该是:

["string, duppi, du", "23", "lala"]
Run Code Online (Sandbox Code Playgroud)

有没有任何跨浏览器解决方案?

rid*_*ner 193

放弃

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

非标准CSV解决方案

正如austincheney正确指出的那样,如果你想正确处理可能包含转义字符的带引号的字符串,你真的需要从头到尾解析字符串.此外,OP没有明确定义"CSV字符串"究竟是什么.首先,我们必须定义什么构成有效的CSV字符串及其各个值.

给定:"CSV String"定义

出于本讨论的目的,"CSV字符串"由零个或多个值组成,其中多个值由逗号分隔.每个值可能包括:

  1. 双引号字符串.(可能包含未转义的单引号.)
  2. 单引号字符串.(可能包含未转义的双引号.)
  3. 未引用的字符串.(不得包含引号,逗号或反斜杠.)
  4. 空值.(所有空白值都被视为空.)

规则/注意事项:

  • 带引号的值可能包含逗号.
  • 引用的值可能包含转义任何内容,例如'that\'s cool'.
  • 必须引用包含引号,逗号或反斜杠的值.
  • 必须引用包含前导或尾随空格的值.
  • 反斜杠将从all \'引用中删除:单引号值.
  • 反斜杠将从所有:\"中删除双引号值.
  • 任何前导和尾随空格都会修剪非引用字符串.
  • 逗号分隔符可以具有相邻的空格(被忽略).

找:

一种JavaScript函数,用于将有效的CSV字符串(如上所述)转换为字符串值数组.

解:

此解决方案使用的正则表达式很复杂.并且(恕我直言)所有非平凡的正则表达式都应该以自由间隔模式呈现,并带有大量的注释和缩进.不幸的是,JavaScript不允许自由间隔模式.因此,此解决方案实现的正则表达式首先以本机正则表达式语法呈现(使用Python方便的表示:r'''...'''raw-multi-line-string语法).

首先是一个正则表达式,它验证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.
"""
Run Code Online (Sandbox Code Playgroud)

如果字符串与上述正则表达式匹配,则该字符串是有效的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.
"""
Run Code Online (Sandbox Code Playgroud)

请注意,此正则表达式不匹配有一个特殊情况值 - 该值为空时的最后一个值.这个特殊的"空的最后一个值"案例由下面的js函数测试和处理.

用于解析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;
};
Run Code Online (Sandbox Code Playgroud)

示例输入和输出:

在以下示例中,花括号用于分隔{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} */
Run Code Online (Sandbox Code Playgroud)
// Test 2: Empty CSV string.
var test = "";
var a = CSVtoArray(test);
/* Array hes 0 elements: */
Run Code Online (Sandbox Code Playgroud)
// Test 3: CSV string with two empty values.
var test = ",";
var a = CSVtoArray(test);
/* Array hes 2 elements:
    a[0] = {}
    a[1] = {} */
Run Code Online (Sandbox Code Playgroud)
// 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} */
Run Code Online (Sandbox Code Playgroud)
// 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} */
Run Code Online (Sandbox Code Playgroud)
// 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] = {} */
Run Code Online (Sandbox Code Playgroud)

补充说明:

此解决方案要求CSV字符串为"有效".例如,未加引号的值可能不包含反斜杠或引号,例如以下CSV字符串无效:

var invalid1 = "one, that's me!, escaped \, comma"
Run Code Online (Sandbox Code Playgroud)

这不是真正的限制,因为任何子字符串都可以表示为单引号或双引号.另请注意,此解决方案仅代表一种可能的定义:"逗号分隔值".

编辑次数:2014-05-19:添加了免责声明. 编辑:2014-12-01:将免责声明移至顶部.

  • 我赞赏细节并澄清你的答案,但应该注意的是,你的CSV定义不适合RFC 4180,这是CSV的标准,我可以说通常使用传闻.特别是这将是在字符串字段中"转义"双引号字符的常规方法:"字段一","字段二","一个""最后""字段包含两个双引号""我没有测试了Trevor Dixon在这个页面上的答案,但这是一个解决RFC 4180 CSV定义的答案. (3认同)
  • @Evan Plaice - 欢迎您将我的任何正则表达用于您想要的任何目的.承认的注意事项会很好但不是必要的.祝你的插件好运.干杯! (2认同)

nir*_*iry 36

RFC 4180解决方案

这不解决问题中的字符串,因为它的格式不符合RFC 4180; 可接受的编码是双引号的双引号.以下解决方案可正常使用谷歌电子表格中的CSV文件d/l.

更新时间(3/2017)

解析单行是错误的.根据RFC 4180字段可能包含CRLF,这将导致任何行读取器中断CSV文件.这是一个解析CSV字符串的更新版本:

'use strict';

function csvToArray(text) {
    let p = '', row = [''], ret = [row], i = 0, r = 0, s = !0, l;
    for (l of text) {
        if ('"' === l) {
            if (s && l === p) row[i] += l;
            s = !s;
        } else if (',' === l && s) l = row[++i] = '';
        else if ('\n' === l && s) {
            if ('\r' === p) row[i] = row[i].slice(0, -1);
            row = ret[++r] = [l = '']; i = 0;
        } else row[i] += l;
        p = l;
    }
    return ret;
};

let test = '"one","two with escaped """" double quotes""","three, with, commas",four with no quotes,"five with CRLF\r\n"\r\n"2nd line one","two with escaped """" double quotes""","three, with, commas",four with no quotes,"five with CRLF\r\n"';
console.log(csvToArray(test));
Run Code Online (Sandbox Code Playgroud)

老答复

(单线解决方案)

function CSVtoArray(text) {
    let ret = [''], i = 0, p = '', s = true;
    for (let l in text) {
        l = text[l];
        if ('"' === l) {
            s = !s;
            if ('"' === p) {
                ret[i] += '"';
                l = '-';
            } else if ('' === p)
                l = '-';
        } else if (s && ',' === l)
            l = ret[++i] = '';
        else
            ret[i] += l;
        p = l;
    }
    return ret;
}
let test = '"one","two with escaped """" double quotes""","three, with, commas",four with no quotes,five for fun';
console.log(CSVtoArray(test));
Run Code Online (Sandbox Code Playgroud)

为了好玩,以下是从阵列创建CSV的方法:

function arrayToCSV(row) {
    for (let i in row) {
        row[i] = row[i].replace(/"/g, '""');
    }
    return '"' + row.join('","') + '"';
}

let row = [
  "one",
  "two with escaped \" double quote",
  "three, with, commas",
  "four with no quotes (now has)",
  "five for fun"
];
let text = arrayToCSV(row);
console.log(text);
Run Code Online (Sandbox Code Playgroud)

  • 这个为我完成了工作,而不是另一个 (2认同)

Ham*_*rNL 9

我喜欢 FakeRainBrigand 的回答,但是它包含一些问题:它不能处理引号和逗号之间的空格,并且不支持 2 个连续的逗号。我尝试编辑他的答案,但我的编辑被显然不理解我的代码的审阅者拒绝了。这是我的 FakeRainBrigand 代码版本。还有一个小提琴:http : //jsfiddle.net/xTezm/46/

String.prototype.splitCSV = function() {
        var matches = this.match(/(\s*"[^"]+"\s*|\s*[^,]+|,)(?=,|$)/g);
        for (var n = 0; n < matches.length; ++n) {
            matches[n] = matches[n].trim();
            if (matches[n] == ',') matches[n] = '';
        }
        if (this[0] == ',') matches.unshift("");
        return matches;
}

var string = ',"string, duppi, du" , 23 ,,, "string, duppi, du",dup,"", , lala';
var parsed = string.splitCSV();
alert(parsed.join('|'));
Run Code Online (Sandbox Code Playgroud)


小智 6

我有一个非常具体的用例,我想将 Google 表格中的单元格复制到我的网络应用程序中。单元格可以包含双引号和换行符。使用复制和粘贴,单元格由制表符分隔,奇数数据的单元格用双引号引起来。我尝试了这个主要的解决方案,链接文章使用正则表达式、Jquery-CSV 和 CSVToArray。 http://papaparse.com/ 是唯一一个开箱即用的。复制和粘贴与带有默认自动检测选项的 Google 表格无缝连接。


Bri*_*and 5

人们似乎为此反对 RegEx。为什么?

(\s*'[^']+'|\s*[^,]+)(?=,|$)
Run Code Online (Sandbox Code Playgroud)

这是代码。我也做了一个小提琴

String.prototype.splitCSV = function(sep) {
  var regex = /(\s*'[^']+'|\s*[^,]+)(?=,|$)/g;
  return matches = this.match(regex);    
}

var string = "'string, duppi, du', 23, 'string, duppi, du', lala";

console.log( string.splitCSV()  );
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)

  • 嗯,您的正则表达式确实存在一些问题:它无法处理引号和逗号之间的空格,并且不支持 2 个连续的逗号。我已经用解决这两个问题的代码更新了你的答案并制作了一个新的小提琴:http://jsfiddle.net/xTezm/43/ (3认同)
  • @niry 我这里的代码很糟糕。我保证在过去的 6 年里我变得更好了 :-p (2认同)

Tre*_*xon 5

PEG(.js)语法,用于处理http://en.wikipedia.org/wiki/Comma-separated_values中的 RFC 4180示例:

start
  = [\n\r]* first:line rest:([\n\r]+ data:line { return data; })* [\n\r]* { rest.unshift(first); return rest; }

line
  = first:field rest:("," text:field { return text; })*
    & { return !!first || rest.length; } // ignore blank lines
    { rest.unshift(first); return rest; }

field
  = '"' text:char* '"' { return text.join(''); }
  / text:[^\n\r,]* { return text.join(''); }

char
  = '"' '"' { return '"'; }
  / [^"]
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/knvzk/10https://pegjs.org/online进行测试.

通过https://gist.github.com/3362830下载生成的解析器.


Pet*_*eny 5

使用正则表达式的 RFC 4180 解决方案

正则表达式来救援!这几行代码根据 RFC 4180 标准正确处理带有嵌入逗号、引号和换行符的引用字段。

function parseCsv(data, fieldSep, newLine) {
  fieldSep = fieldSep || ',';
  newLine = newLine || '\n';
  const nSep = '\x1D'; const nSepRe = new RegExp(nSep, 'g');
  const qSep = '\x1E'; const qSepRe = new RegExp(qSep, 'g');
  const cSep = '\x1F'; const cSepRe = new RegExp(cSep, 'g');
  const fieldRe = new RegExp('(^|[' + fieldSep + '\\n])"([^"]*(?:""[^"]*)*)"(?=($|[' + fieldSep + '\\n]))', 'g');
  return data
    .replace(/\r/g, '')
    .replace(/\n+$/, '')
    .replace(fieldRe, (match, p1, p2) => {
      return p1 + p2.replace(/\n/g, nSep).replace(/""/g, qSep).replace(/,/g, cSep)
    })
    .split(/\n/)
    .map(line => {
      return line
        .split(fieldSep)
        .map(cell => cell.replace(nSepRe, newLine).replace(qSepRe, '"').replace(cSepRe, ','))
    });
}

const csv = 'A1,B1,C1\n"A ""2""","B, 2","C\n2"';
const separator = ',';      // field separator, default: ','
const newline = ' <br /> '; // newline representation in case a field contains newlines, default: '\n' 
let grid = parseCsv(csv, separator, newline);
// expected: [ [ 'A1', 'B1', 'C1' ], [ 'A "2"', 'B, 2', 'C <br /> 2' ] ]
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 可以配置字段分隔符,例如\tTSV(制表符分隔值)
  • 嵌入的换行符可以转换为其他内容,例如<br/>用于 HTML 使用
  • parseCsv函数可避免负/正向后查找,例如也适用于 Safari 浏览器。

除非另有说明,否则您不需要有限状态机。由于使用临时替换/恢复、捕获组和正向前瞻的函数式编程方法,正则表达式可以正确处理 RFC 4180。

克隆/下载代码:https://github.com/peterthoeny/parse-csv-js

了解有关正则表达式的更多信息: https://twiki.org/cgi-bin/view/Codev/TWikiPresentation2018x10x14Regex

使用 Lookbehinds 的旧答案

(这不适用于 Safari 浏览器)

function parseCsv(data, fieldSep, newLine) {
    fieldSep = fieldSep || ',';
    newLine = newLine || '\n';
    var nSep = '\x1D';
    var qSep = '\x1E';
    var cSep = '\x1F';
    var nSepRe = new RegExp(nSep, 'g');
    var qSepRe = new RegExp(qSep, 'g');
    var cSepRe = new RegExp(cSep, 'g');
    var fieldRe = new RegExp('(?<=(^|[' + fieldSep + '\\n]))"(|[\\s\\S]+?(?<![^"]"))"(?=($|[' + fieldSep + '\\n]))', 'g');
    var grid = [];
    data.replace(/\r/g, '').replace(/\n+$/, '').replace(fieldRe, function(match, p1, p2) {
        return p2.replace(/\n/g, nSep).replace(/""/g, qSep).replace(/,/g, cSep);
    }).split(/\n/).forEach(function(line) {
        var row = line.split(fieldSep).map(function(cell) {
            return cell.replace(nSepRe, newLine).replace(qSepRe, '"').replace(cSepRe, ',');
        });
        grid.push(row);
    });
    return grid;
}

const csv = 'A1,B1,C1\n"A ""2""","B, 2","C\n2"';
const separator = ',';      // field separator, default: ','
const newline = ' <br /> '; // newline representation in case a field contains newlines, default: '\n' 
var grid = parseCsv(csv, separator, newline);
// expected: [ [ 'A1', 'B1', 'C1' ], [ 'A "2"', 'B, 2', 'C <br /> 2' ] ]
Run Code Online (Sandbox Code Playgroud)


小智 5

我已经多次使用正则表达式,但每次我总是必须重新学习它,这很令人沮丧:-)

所以这是一个非正则表达式的解决方案:

function csvRowToArray(row, delimiter = ',', quoteChar = '"'){
    let nStart = 0, nEnd = 0, a=[], nRowLen=row.length, bQuotedValue;
    while (nStart <= nRowLen) {
        bQuotedValue = (row.charAt(nStart) === quoteChar);
        if (bQuotedValue) {
            nStart++;
            nEnd = row.indexOf(quoteChar + delimiter, nStart)
        } else {
            nEnd = row.indexOf(delimiter, nStart)
        }
        if (nEnd < 0) nEnd = nRowLen;
        a.push(row.substring(nStart,nEnd));
        nStart = nEnd + delimiter.length + (bQuotedValue ? 1 : 0)
    }
    return a;
}
Run Code Online (Sandbox Code Playgroud)

怎么运行的:

  1. 传入 csv 字符串row
  2. 当下一个值的开始位置位于行内时,请执行以下操作:
    • 如果该值已被引用,则设置nEnd为收盘价。
    • 否则,如果值未被引用,则设置nEnd为下一个分隔符。
    • 将值添加到数组中。
    • 设置nStartnEnd加上分隔符的长度。

有时编写自己的小函数比使用库更好。您自己的代码将运行良好并且只占用很小的空间。此外,您可以轻松调整它以满足您自己的需求。

  • 谢谢@保罗!一个小小的改进。我将 `if (nEnd &lt; 0) nEnd = nRowLen` 替换为 ```if (nEnd &lt; 0 ) { if (bQuotedValue == true) {nEnd = nRowLen - 1} else {nEnd = nRowLen} }``` 以适应对于以引号结尾的行。我希望这是有道理的。 (2认同)