首頁 >web前端 >js教程 >JavaScript 如何有效解析引用欄位中帶有逗號的 CSV 字串?

JavaScript 如何有效解析引用欄位中帶有逗號的 CSV 字串?

Barbara Streisand
Barbara Streisand原創
2024-12-08 11:46:11333瀏覽

How Can JavaScript Effectively Parse CSV Strings with Commas in Quoted Fields?

使用JavaScript 處理引用的CSV 欄位中的逗號

在JavaScript 中處理CSV(逗號分隔值)字串時,解析可以當資料可以在引用欄位中包含逗號時,這將具有挑戰性。以下是如何透過詳細的解決方案有效處理這種情況:

用於驗證和解析CSV 字串的正規表示式

確保輸入字串是有效的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中解析各個值字串,我們使用以下正規表示式:

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 : Single quoted string,
| "([^"\]*(?:\[\S\s][^"\]*)*)"   # or : Double quoted string,
| ([^,'"\s\]*(?:\s+[^,'"\s\]+)*)  # or : Non-comma, non-quote stuff.
)                                   # End group of value alternatives.
\s*                                 # Strip whitespace after value.
(?:,|$)                             # Field ends on comma or EOS.
"""

CSV 解析函數

定義這些正規表示式後,我們可以實作一個解析CSV 字串的函數:

function CSVtoArray(text) {
  // 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;
}

範例用法

以下是輸入CSV 字串及其對應解析輸出的一些範例:

// Test string from original question
let result = CSVtoArray("'string, duppi, du', 23, lala");
console.log(result);  // ['string, duppi, du', '23', 'lala']

// Empty CSV string
let result = CSVtoArray("");
console.log(result);  // []

// CSV string with two empty values
let result = CSVtoArray(",");
console.log(result);  // ['', '']

// Double quoted CSV string having single quoted values
let result = CSVtoArray("'one','two with escaped \' single quote', 'three, with, commas'");
console.log(result);  // ['one', 'two with escaped \' single quote', 'three, with, commas']

// Single quoted CSV string having double quoted values
let result = CSVtoArray('"one","two with escaped \" double quote", "three, with, commas"');
console.log(result);  // ['one', 'two with escaped " double quote', 'three, with, commas']

// CSV string with whitespace in and around empty and non-empty values
let result = CSVtoArray("   one  ,  'two'  ,  , ' four' ,, 'six ', ' seven ' ,  ");
console.log(result);  // ['one', 'two', '', 'four', '', 'six ', ' seven ']

// Not valid
let result = CSVtoArray("one, that's me!, escaped \, comma");
console.log(result);  // null

此解決方案可確保準確解析CSV 字串,處理包含逗號的引用字段,同時堅持達到指定要求。

以上是JavaScript 如何有效解析引用欄位中帶有逗號的 CSV 字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn