I need to split a comma separated string, which contents are sometimes between quotes. An example could be:
1,"TEST",22345,"18,95", Ab"cde
The first problem here is to split the string only when the comma is not surrounded by quotes like "18,95". I've done that with a simple Regex. The next problem is to cut out the quotes, where they surround the content. For "TEST" and "18,95" the quotes should be removed.The quote in Ab"cde should be left untouched. Here is my code so far:
List<string> results = Regex.Matches(this.Content, @"[\""](.+?)[\""]|[^,]+")
.Cast<Match>()
.Select(m => m.Value)
.Select(s => s.StartsWith("\"") && s.EndsWith("\"") ? s.Remove(1,1).Remove(s.Length-1,1) : s)
.ToList();
For the second Select
I get an ArgumentOutOfRangeException
since the second Remove
doesn't work with s
anymore. I thought it should work, but somehow doesn't.
If there is a better way to do this I would be happy to learn about it.