0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CSV/TSVファイルのセル内改行に正規表現で対応する

Last updated at Posted at 2021-12-01

ダブルクォーテーションで囲ったセル内改行がある場合、そのまま改行コードでsplitしてしまうと結果の配列が崩れてしまいます。
行列の改行コードとセル内改行の改行コードを分けることで対応できます。

const csvDelimiter = ","
const tsvDelimiter = "\t"
xhr.responseText
    .replace(/(?<=\t)(?!\"\")(?!\\\")\"[\s\S]*?(?!\"\")(?!\\\")\"(?=\t)(?=\r\n)/g, (match) => {
        return match.replace(/\r\n/g, "\n")// セル内改行の改行コードCRLFをLFに変換
    })// / \t + [""|\"]でない + " + 行またぎ含んだ文字列 + [""or\"]でない + " + [\t|\r\n]である  /
    .split(/\r\n/)//CRLF改行で区切る LFはセル内改行なので区切らない
    .map(line => line.split(tsvDelimiter ))//区切り文字で区切る
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?