0

I am creating a string array of comma separated values. I need to split the line on commas but not commas that are inside quotes as that could be part of the data.

For example:
\"421 15th Ave.\",\"Beaver Falls, PA\",\"S1\",

I wouldn't want it to split between the city and state for a new field.

Here is the code currently:

string[] fields = Regex.Split(lines[i], @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))");

It takes a long time to execute. Is there a better option I could be using?

Thanks for any help on this.

4
  • Are you required to use regex? CSV is often best tackled using plain old string methods. Commented Dec 10, 2013 at 16:01
  • 1
    I am not required to use regex that is just what is currently in place. Looking for a better option. Which string method(s) would you suggest to solve this? Commented Dec 10, 2013 at 16:08
  • 2
    Use some sort of csv reader. Assuming you're using a decent one, this will already be handled and the code should be optimized. Commented Dec 10, 2013 at 16:09
  • You might gain even more performance if you parallelize the spliting file lines between processors, using Parallel.ForEach & Parititioner.Create. This way you can process LINES0-1000 on a processor1, and LINES1001-2000 on a processor2, yielding you 2x improvement. Commented Dec 10, 2013 at 16:24

1 Answer 1

1

Have you considered using a CSV-Reader? This CSV-Reader should already handle the case of commas inside double quotes: OpenCsv

See Ravi Thapliyal's answer in this thread about how to use it: link

For C# I can recommend this CsvHelper: https://github.com/JoshClose/CsvHelper

We use it in our project and it's very handy

Sign up to request clarification or add additional context in comments.

3 Comments

Is there a C# equivalent to this?
Hey Baxter I updated my answer just before you commented :-) See the CsvHelper link in my answer above
Hey Baxter if this answer helped I would appreciate, if you could mark it as accepted answer :-) thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.