Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
CSV splitter for lines with escaped delimeters
Converts a csv line which contain escaped elements delimited by for example ". The elements inside these delimters
can contain a , so a simple line.Split(',') would be incorrect.
val line : string = ""22 Dec 2014",BP,"EXPENSES ","1000.00", , "
val toks : string [] = [|"22 Dec 2014"; "BP"; "EXPENSES "; "1000.00"; " "|]
//parse csv char by char
let SplitCSV (line:string) =
let rec csv_splitter (line:string) (escape_char:char) (i:int) (is_in_q:bool) (tok:char[]) (toks:string[]) =
if i = line.Length then
let c = line.[i]
if c = escape_char then
csv_splitter line escape_char (i+1) (not is_in_q) tok toks
elif c = ',' && (not is_in_q) then // actual delimter
let stok = tok |> System.String //convert char[] to string
csv_splitter line escape_char (i+1) (is_in_q) [||] (Array.concat [| toks; [|stok|] |])
csv_splitter line escape_char (i+1) (is_in_q) (Array.concat [| tok; [|c|] |]) toks
//execute splitter with escape char "
csv_splitter line '"' 0 false [||] [||]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment