Last active
October 2, 2017 14:48
-
-
Save markknol/3971853e2b6f81ea4d4454a8fac17128 to your computer and use it in GitHub Desktop.
Haxe CSV Parser / Reader
This file contains 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
using StringTools; | |
class CSVReader | |
{ | |
private static var format:CSVFormat = { del: ",", quote: '"', escape: '""', linedel: "\r\n" }; | |
private var csv:String; | |
public function new(csv:String) | |
{ | |
this.csv = csv; | |
} | |
/** | |
* @return sheet [row [cell, cell], row [cell, cell] ] | |
*/ | |
public function parseSheet():Array<Array<String>> | |
{ | |
inline function replaceQuote(v:String) return v.replace(format.escape, format.quote); | |
return [for (line in csv.split(format.linedel)) | |
{ | |
var ereg = ~/("([^"]*)"|[^,]*)(,|$)/; | |
var rows = []; | |
while(ereg.match(line)) | |
{ | |
var cell = ereg.matched(1); | |
if (cell.startsWith(format.quote) && cell.endsWith(format.quote)) | |
{ | |
// unquote | |
cell = cell.substr(format.quote.length, cell.length - format.quote.length * 2); | |
} | |
rows.push(cell); | |
line = ereg.matchedRight(); | |
if (line.length == 0) break; | |
} | |
rows; | |
}]; | |
} | |
} | |
typedef CSVFormat = { | |
del:String, // delimiter for columns | |
quote:String, // quote wrapped around cell | |
escape:String, // escaped quote in cell | |
linedel:String, // delimiter for rows | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment