Created
April 8, 2022 13:51
-
-
Save NikolaiRuhe/a1b137bad0dfd8bee0d6d1dcba79f2e4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func testCSV() throws { | |
let plainField = Prefix { $0 != .init(ascii: ",") && $0 != .init(ascii: "|") && $0 != .init(ascii: "\n") } | |
let quotedField = Parse { | |
"|".utf8 | |
Many { | |
OneOf { | |
Parse { "||".utf8 }.map { Substring("").utf8 } | |
Prefix { $0 != .init(ascii: "|") } | |
} | |
} separator: { | |
"".utf8 | |
} | |
"|".utf8 | |
}.map { array in | |
array.map(Substring.init).joined(separator: "")[...].utf8 | |
} | |
// .eraseToAnyParser() | |
let field = OneOf { | |
quotedField | |
plainField | |
} | |
.map { String(Substring($0)) } | |
let line = Many { | |
field | |
} separator: { | |
",".utf8 | |
} | |
let csv = Many { | |
line | |
} separator: { | |
"\n".utf8 | |
} terminator: { | |
End() | |
} | |
let input = #""" | |
123,Alice | |
789,|Clarice| | |
456,|Bob ||Baumeister||| | |
"""# | |
let result = try csv.parse(input) | |
XCTAssertNoDifference([["123", "Alice"], ["789", "Clarice"], ["456", "Bob |Baumeister|"]], result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment