CSV 解析 - Swift 4

Sha*_*jan 2 csv ios swift

我正在尝试解析 CSV,但遇到了一些问题。以下是我用于解析 CSV 的代码:

let fileURL = Bundle.main.url(forResource: "test_application_data - Sheet 1", withExtension: "csv")
let content = try String(contentsOf: fileURL!, encoding: String.Encoding.utf8)
let parsedCSV: [[String]] = content.components(separatedBy: "\n").map{ $0.components(separatedBy: ",")}
Run Code Online (Sandbox Code Playgroud)

这是我正在解析的 CSV 中的数据:

Item 9,Description 9,image url 
"Item 10 Extra line 1 Extra line 2 Extra line 3",Description 10,image url
Run Code Online (Sandbox Code Playgroud)

因此,通过使用上面的代码,我得到了第一行的正确响应,即Item 9但我得到了格式错误的响应Item 10

如何正确解析两行?

在此处输入图片说明

OOP*_*Per 6

CSV 的 RFC:逗号分隔值 (CSV) 文件的通用格式和 MIME 类型 (RFC-4180)

并非所有 CSV 数据或 CSV 处理器都符合此 RFC 的所有描述,但通常,双引号内的字段可以包含:

  • 换行
  • 逗号
  • 转义双引号(""表示单个双引号)

这段代码比 RFC-4180 稍微简化了一点,但处理了上述所有三种情况:

更新这个旧代码不能很好地处理 CRLF。(这是 RFC-4180 中的有效换行符。)我在底部添加了一个新代码,请检查它。感谢杰。

import Foundation

let csvText = """
Item 9,Description 9,image url
"Item 10
Extra line 1
Extra line 2
Extra line 3",Description 10,image url
"Item 11
Csv item can contain ""double quote"" and comma(,)", Description 11 ,image url
"""

let pattern = "[ \r\t]*(?:\"((?:[^\"]|\"\")*)\"|([^,\"\\n]*))[ \t]*([,\\n]|$)"
let regex = try! NSRegularExpression(pattern: pattern)

var result: [[String]] = []
var record: [String] = []
let offset: Int = 0
regex.enumerateMatches(in: csvText, options: .anchored, range: NSRange(0..<csvText.utf16.count)) {match, flags, stop in
    guard let match = match else {fatalError()}
    if match.range(at: 1).location != NSNotFound {
        let field = csvText[Range(match.range(at: 1), in: csvText)!].replacingOccurrences(of: "\"\"", with: "\"")
        record.append(field)
    } else if match.range(at: 2).location != NSNotFound {
        let field = csvText[Range(match.range(at: 2), in: csvText)!].trimmingCharacters(in: .whitespaces)
        record.append(field)
    }
    let separator = csvText[Range(match.range(at: 3), in: csvText)!]
    switch separator {
    case "\n": //newline
        result.append(record)
        record = []
    case "": //end of text
        //Ignoring empty last line...
        if record.count > 1 || (record.count == 1 && !record[0].isEmpty) {
            result.append(record)
        }
        stop.pointee = true
    default: //comma
        break
    }
}
print(result)
Run Code Online (Sandbox Code Playgroud)

(打算在操场上测试。)


新代码,CRLF 就绪。

import Foundation

let csvText =  "Field0,Field1\r\n"

let pattern = "[ \t]*(?:\"((?:[^\"]|\"\")*)\"|([^,\"\r\\n]*))[ \t]*(,|\r\\n?|\\n|$)"
let regex = try! NSRegularExpression(pattern: pattern)

var result: [[String]] = []
var record: [String] = []
let offset: Int = 0
regex.enumerateMatches(in: csvText, options: .anchored, range: NSRange(0..<csvText.utf16.count)) {match, flags, stop in
    guard let match = match else {fatalError()}
    if let quotedRange = Range(match.range(at: 1), in: csvText) {
        let field = csvText[quotedRange].replacingOccurrences(of: "\"\"", with: "\"")
        record.append(field)
    } else if let range = Range(match.range(at: 2), in: csvText) {
        let field = csvText[range].trimmingCharacters(in: .whitespaces)
        record.append(field)
    }
    let separator = csvText[Range(match.range(at: 3), in: csvText)!]
    switch separator {
    case "": //end of text
        //Ignoring empty last line...
        if record.count > 1 || (record.count == 1 && !record[0].isEmpty) {
            result.append(record)
        }
        stop.pointee = true
    case ",": //comma
        break
    default: //newline
        result.append(record)
        record = []
    }
}
print(result) //->[["Field0", "Field1"]]
Run Code Online (Sandbox Code Playgroud)