0

General Info
Working on a game mod where users are able to insert custom data into a configuration file using a basic string.

The problem
I'm trying to split the string in such a way that data is clearly separable without limiting user input, with the exception of quotes. The issue is that the approaches I've tried did not deliver the expected result.

Exampe input / output
String input:

String str = "'Item Name:Item ID','Item name with, comma:Some ID','Some Name:Some ID'";

Expected output:

'Item Name:Item ID'
'Item name with, comma:Some ID'
'Some Name:Some ID'

The single quotes in the output are not important to me, but the colon is (as to separate names with IDs)

What I've tried myself

String str = "'Item Name:Item ID','Item name with, comma:Some ID','Some Name:Some ID'";
        
String[] separator = { "','" };
Int32 count = 100;

String[] strlist = str.Split(separator, count, StringSplitOptions.RemoveEmptyEntries);

foreach(String s in strlist)
{
    Console.WriteLine(s);
}

Result output:

'Item Name:Item ID
Item name with, comma:Some ID
Some Name:Some ID'

I've also tried String[] separator = { "," }; instead, with the result:

'Item Name:Item ID'
'Item name with
 comma:Some ID'
'Some Name:Some ID'

How should I adept my code to get the desired result?

icecub
  • 8,615
  • 6
  • 41
  • 70
  • 2
    You have actually a CVS format (with `'` as a *quotation mark* and `,` as a *separator*), just try any *CsvParsers* – Dmitry Bychenko Feb 07 '23 at 14:43
  • 1
    Look at [this](https://stackoverflow.com/questions/6542996/how-to-split-csv-whose-columns-may-contain-comma) – FortyTwo Feb 07 '23 at 14:45
  • 1
    @FortyTwo Thanks a lot for that example and thanks Dmitry for the advise. I think this question can be closed as a duplicate of that question FortyTwo :) – icecub Feb 07 '23 at 14:47
  • 1
    You can use [`Regex.Split()`](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.split?view=net-7.0) with `"(?<='),(?=')"` as pattern (positives lookahead and lookbehind won't be part of the split) – Cid Feb 07 '23 at 14:52

0 Answers0