I am using dataloader and retrieve data like that:

"0017Q000003T1EdQAK","sForce ""Test"" ","Some,data","","94087",""

And i need to split it by comma, but how can i do it? I didn't find any good ideas and most is just splitting by "," which is not a way. And cause of quotes inside of field value its hard to make something else. So for know i can do only something like that.

String str = ' "0017Q000003T1EdQAK","sForce ""Test"" ","Some,data","","94087",123';

I think i can just count " and check if odd. Is it right way?

  • 2
    Could you go into more detail about why split(',') doesn't do what you need? That is literally what you do to split a string by commas.
    – Derek F
    Oct 29, 2021 at 13:07
  • @DerekF there might be a data without " ". So i want to split only by comma outside qoutes and not depending only on quote. So i think its nice to count " cause inside there are always 1,3,5 and so on quotes.
    – Vupsen'
    Oct 29, 2021 at 13:20
  • Whats does str.split(yourArray) give you? Oct 29, 2021 at 13:33
  • my favorite apex CSV parser
    – cropredy
    Oct 29, 2021 at 22:50

1 Answer 1


Parsing a CSV correctly and efficiently requires a finite-state automaton (FSA), or more simply, a state machine. It's not simply enough to count quotes or split by commas, etc. The implementation should follow RFC 4180, which is pretty easy to implement as an FSA.

With an FSA, you create a "machine" that has various states, such as "start of line," "start of escape sequence," "start of cell," "end of cell," "end of line," and "end of file." The FSA reads each character and makes a decision based on the FSA state. I actually recently wrote a few different versions that you can reference, as well as the original reference material from Daniel Ballinger.

Note that quoted cells can also have embedded newlines, so you'll find that real CSVs, if that is your goal, are more complicated than you may believe. If you end up trying to use split, you'll also end up having to do joins later, and the work gets a lot more complicated.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .