One-Line CSV Parser for ActionScript, AS3, Flex, AIR

Well, okay, it’s slightly more than a line, but still I wish someone had written a blog post like this when I went out looking for a CSV parser for YNAB 3.

Thanks to comments in this blog, I discovered that you can split a CSV line, and correctly account for escaped commas, doublequotes, etc, with the following expression:

For each line of text in your CSV file, just do this:
[code lang="as3"]
var components : Array = line.split(/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/g);
[/code]

There are some side effects, like quotes that are used to wrap values are still included in the components, but it was a small price to pay. I think it beats the typical state machine approach. (Well, I say that cause I didn’t have to come up with that beast of a Regular Expression).

Now you’ve got your array of values for your csv line. I’m sure you can take it from here.

Tags: ,

4 Responses to “One-Line CSV Parser for ActionScript, AS3, Flex, AIR”

  1. poco May 3, 2010 at 1:47 am #

    a brilliant regexp, thank you for posting it

  2. a guy June 24, 2010 at 6:08 am #

    thanks. this was very useful to me also…

  3. jaume mussons September 15, 2010 at 1:33 am #

    Hi I made an actionscript method that converts a full csv file data to an array. I don’t know if it is faster that using regular expressions. Anyone knows which is faster??

    Here’s my method:

    http://jaumemussons.wordpress.com/2010/08/29/flex-actionscript-csv-parse-convert-csv-string-to-array/

  4. Adrian July 24, 2013 at 4:43 am #

    Brilliant!

Leave a Reply