-2

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!

7
  • 1
    where is your code?
    – Riad
    Commented Apr 27, 2017 at 11:50
  • 2
    I recommend getting a CSV parser, while this sort of thing can be done in regular expressions, it's not worth it.
    – juharr
    Commented Apr 27, 2017 at 11:50
  • @juharr Can a CSV parser do that?
    – Azeros
    Commented Apr 27, 2017 at 11:51
  • @Riad I already wrote that nothing I tried worked... There's no need for my code...
    – Azeros
    Commented Apr 27, 2017 at 11:52
  • Yes, you might have to configure it to use single quotes but this is exactly what a CSV parser is for.
    – juharr
    Commented Apr 27, 2017 at 11:52

3 Answers 3

2

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

1
  • Thank you very much! Спасибо
    – Azeros
    Commented Apr 27, 2017 at 12:11
2

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.

1
  • 1
    A difficulty can appear if we want to include quotation symbol (' 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
1

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.

2
  • A bit weird counter example: in CSV we double quotation symbol if we want to include it: "'x,''y',2,4,'y,z'" should be parsed as ['x,''y', 2, 4, 'y,z'] Commented Apr 27, 2017 at 12:14
  • @DmitryBychenko: yes, you're right, my code would fail on such input. That's why I explicitly restricted the cases where this is applicable. I just wanted to share a simple on-line solution for the cases where no quotes inside quotes expected. Commented Apr 27, 2017 at 12:22

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.