Go中的CSV編碼:處理帶引號的字串
在Go的encoding/csv包中,處理引號的字符串有時會導致意想不到的結果。在編寫 CSV 記錄時,了解編碼特殊字元(例如雙引號)的標準要求至關重要。
根據 CSV 規範,欄位中的雙引號字元必須使用第二個雙引號字元進行轉義。出於解析原因,此轉義序列是必需的。
範例:
<code class="go">import "encoding/csv" record := []string{ "Unquoted string", "Cr@zy text with , and \ and \" etc", } writer := csv.NewWriter(writer) writer.Write(record)</code>
上面的程式碼將寫入雙引號轉義的字串:
<code class="csv">Unquoted string "Cr@zy text with , and \ and \" etc"</code>
避免額外引號:
要避免在讀取CSV 檔案時插入額外引號,應採取以下步驟:
程式碼範例:
<code class="go">func writeCSV() { writer := csv.NewWriter(writer) s := "Cr@zy text with , and \ and \" etc" record := []string{ "Unquoted string", "Quoted string", fmt.Sprintf("%q", s), } writer.Write(record) } func readCSV() { reader := csv.NewReader(reader) records, err := reader.ReadAll() for _, record := range records { // Printed records automatically have double quotes unescaped by the CSV reader. fmt.Println(record) } }</code>
輸出:
[Unquoted string Cr@zy text with , and \ and " etc] [Quoted string Cr@zy text with , and \ and " etc]
以上是如何使用 Go 的 `encoding/csv` 套件處理 CSV 編碼中帶引號的字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!