Sparse 0.4.0

Sparse 0.4.0

测试已测试
语言语言 SwiftSwift
许可证 MIT
发布最后发布2019 年 11 月
SPM支持 SPM

John Morgan 维护。



Sparse 0.4.0

✂️Sparse✂️

Version License Swift

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

安装

Swift 包管理器

将 Sparse 作为依赖项添加到 Package.swift 中

.package(url: "https://github.com/johnpatrickmorgan/sparse.git", from: "0.3.0"),

CocoaPods

将以下行添加到 Podfile 中

pod "Sparse"

信用

Sparse基于Haskell的Parsec

许可证

Sparse可在MIT许可证下使用。有关更多信息,请参阅LICENSE文件。