使用 JavaScript 拆分 CSV

Split a CSV with javascript

本文关键字:CSV 拆分 JavaScript 使用      更新时间:2023-09-26

有没有办法使用 javascript 拆分 CSV 字符串,其中分隔符也可以作为转义值出现。其他正则表达式实现通过回溯解决了这个问题,但由于 javascript 不支持回溯,我想知道如何使用正则表达式以整洁的方式完成此操作。

csv 行可能如下所示

"This is', a value",Hello,4,'This is also', possible',true

这必须拆分为(包含的字符串)

[0] => "This is', a value"
[1] => Hello
[2] => 4
[3] => 'This is also', possible'
[4] => true

与其尝试拆分,不如尝试使用以下模式对所有不是,的全局匹配:

/"[^"]+"|'[^']+'|[^,]+/g
例如,

您可以使用以下正则表达式:

(.*?[^''])(,|$)

正则表达式采用所有内容 .*? 直到第一个逗号,它前面没有 '',或行尾

这里有一些将 csv 更改为 json 的代码(假设第一行是它道具名称)。 你可以拿第一部分(array2d)并用它非常轻松地做其他事情。

// split rows by 'r'n.  Not sure if all csv has this, but mine did
const rows = rawCsvFile.split("'r'n");
// find all commas, or chunks of text in quotes.  If not in quotes, consider it a split point
const splitPointsRegex = /"(""|[^"])+?"|,/g;
const array2d = rows.map((row) => {
    let lastPoint = 0;
    const cols: string[] = [];
    let match: RegExpExecArray;
    while ((match = splitPointsRegex.exec(row)) !== null) {
        if (match[0] === ",") {
            cols.push(row.substring(lastPoint, match.index));
            lastPoint = match.index + 1;
        }
    }
    cols.push(row.slice(lastPoint));
    // remove leading commas, wrapping quotes, and unneeded 'r
    return cols.map((datum) => 
        datum.replace(/^,?"?|"$/g, "")
        .replace(/""/g, `'"`)
        .replace(/'r/g, "")
    );
})
// assuming first row it props name, create an array of objects with prop names of the values given
const out = [];
const propsRow = array2d[0];
array2d.forEach((row, i) => {
    if (i === 0) { return; }
    const addMe: any = {};
    row.forEach((datum, j) => {
        let parsedData: any;
        if (isNaN(Number(datum)) === false) {
            parsedData = Number(datum);
        } else if (datum === "TRUE") {
            parsedData = true;
        } else if (datum === "FALSE") {
            parsedData = false;
        } else {
            parsedData = datum;
        }
        addMe[propsRow[j]] = parsedData;
    });
    out.push(addMe);
});
console.log(out);

不幸的是,这不适用于 Firefox,仅适用于 Chrome 和 Edge:

"abc'',cde,efg".split(/(?<!''),/)将导致["abc',cde", "efg"]

您需要在第二步中删除所有(未转义的)转义。