Sparse 是一个用 Swift 编写的简单解析库。它基于 Haskell 的 Parsec 所使用的解析器组合方法。它的重点是自然语言解析器的创建和描述性错误消息。
这是一个 CSV 解析器
let quote = character("\"")
let illegalCellCharacters = CharacterSet.newlines.union(CharacterSet(charactersIn: ","))
let unquotedCellCharacter = characterNot(in: illegalCellCharacters)
.named("cell character")
let unquotedCell = many(unquotedCellCharacter).asString()
.map { $0.trimmingCharacters(in: .whitespaces) }
let escapedQuote = quote.skipThen(quote)
.named("escaped quote")
let quotedCellCharacter = characterNot("\"")
.named("quoted cell character")
.otherwise(escapedQuote)
let quotedCell = many(quotedCellCharacter, boundedBy: quote).asString()
let cell = quotedCell.otherwise(unquotedCell)
let cellSeparator = whitespaces().then(character(",")).then(whitespaces())
.named("cell separator")
let line = many(cell, separator: cellSeparator)
let ending = optional(newline()).then(end())
let csv = many(line, separator: newline()).thenSkip(ending)
public func parseCSV(input: String) throws -> [[String]] {
return try csv.parse(input)
}
命名组件解析器可以生成更具描述性的错误消息,例如:
Line 8, Column 12
r8c1 , "r8"c2" , r8c3 ,r8c4,r8c5,r8c6,r8c7 , r8c8
~~~~~~~~~~~^
Expected: '"' in escaped quote
Expected: whitespace in cell separator
Expected: ',' in cell separator
Expected: newline
Expected: EOF: file
在 Package.swift 中添加 Sparse 作为依赖项
.package(url: "https://github.com/johnpatrickmorgan/sparse.git", from: "0.3.0"),
将以下行添加到您的 Podfile 中
pod "Sparse"
Sparse 基于 Haskell 的 Parsec。
Sparse 在 MIT 许可证下可用。 有关更多信息,请参见 LICENSE 文件。