So I have quite a big problem...
I get a string like:
'x,y',2,4,'y,z'
And I need to seperate it into
'x,y'
2
4
'y,z'
Nothing I tried came anywhere near the expected result...
Thanks in advance!
So I have quite a big problem...
I get a string like:
'x,y',2,4,'y,z'
And I need to seperate it into
'x,y'
2
4
'y,z'
Nothing I tried came anywhere near the expected result...
Thanks in advance!
If you're looking for a quick solution, try this (simple loop and no regular expressions):
private static IEnumerable<string> CsvSplitter(string source) {
if (string.IsNullOrEmpty(source))
yield break; //TODO: you may want to throw exception in case source == null
int lastIndex = 0;
bool inQuot = false;
for (int i = 0; i < source.Length; ++i) {
char c = source[i];
if (inQuot)
inQuot = c != '\'';
else if (c == '\'')
inQuot = true;
else if (c == ',') {
yield return source.Substring(lastIndex, i - lastIndex);
lastIndex = i + 1;
}
}
//TODO: you can well have invalid csv (unterminated quotation):
// if (inQuot)
// throw new FormatException("Incorrect CSV");
yield return source.Substring(lastIndex);
}
Sample:
string source = @"'x,y',2,4,'y,z',";
string[] result = CsvSplitter(source).ToArray();
Console.Write(string.Join(Environment.NewLine, result));
Output:
'x,y'
2
4
'y,z'
However, in general case google for CSV parser
If you wanna go the regex way, you can use
('.*?'|[^,]+)
and browse the capture groups, but I strongly recommend you to use a CSV parser.
'
in the case) into data; in CSV we usually double the quotation symbol, e.g.: "'x,''y',2,4,'y,z'"
should be parsed as ['x,''y', 2, 4, 'y,z']
. That's why regular expression seems to be a partial solution and I totally agree with your strong recomendation.
Commented
Apr 27, 2017 at 12:21
If no nested quotes allowed, we can retrieve the required parts with a simple regex '.*?'|[^,]+
:
var input = "'x,y',2,4,'y,z'";
var parts = Regex
.Matches(input, "'.*?'|[^,]+")
.Cast<Match>()
.Select(m => m.Value)
.ToList();
Console.WriteLine(string.Join(Environment.NewLine, parts));
Demo: https://dotnetfiddle.net/qo5aHz
Although .NET flavour allows to elaborate a regex for nested quotes, it would be rather hard and therefore it's best to use a ready-made CSV parser. For example, TextFieldParser
provided with .NET.
"'x,''y',2,4,'y,z'"
should be parsed as ['x,''y', 2, 4, 'y,z']
Commented
Apr 27, 2017 at 12:14