Search code examples
strsplit

Split into string array only the key by comma and not values c#


This is my String and i have problems when splitting into string array with comma seperated values for keys

{ Yr = 2019, Mth = DECEMBER , SeqN = 0, UComment = tet,tet1, OComment = test,test1, FWkMth = WK, FSafety = Y, FCustConsign = Y, FNCNRPull = 0, FNCNRPush = 0, CreatedTime = 2020-01-03 06:16:53 }

when i try to use string.Split(',') i get "Ucomment = tet","tet1" as seperate array. But i need to have split string[] when seperated by comma

UComment = tet,tet1 OComment = test,test1

I have tried using the regex ,(?=([^\"]\"[^\"]\")[^\"]$)" but it didnot work.


Solution

  • You may try matching on the regex pattern \S+\s*=\s*.*?(?=\s*,\s*\S+\s*=|\s*\}$):

    string input = "{ Yr = 2019, Mth = DECEMBER , SeqN = 0, UComment = tet,tet1, OComment = test,test1, FWkMth = WK, FSafety = Y, FCustConsign = Y, FNCNRPull = 0, FNCNRPush = 0, CreatedTime = 2020-01-03 06:16:53 }";
    Regex regex = new Regex(@"\S+\s*=\s*.*?(?=\s*,\s*\S+\s*=|\s*\}$)");
    var results = regex.Matches(input);
    foreach (Match match in results)
    {
        Console.WriteLine(match.Groups[0].Value);
    }
    

    This prints:

    Yr = 2019
    Mth = DECEMBER
    SeqN = 0
    UComment = tet,tet1
    OComment = test,test1
    FWkMth = WK
    FSafety = Y
    FCustConsign = Y
    FNCNRPull = 0
    FNCNRPush = 0
    CreatedTime = 2020-01-03 06:16:53
    

    Here is an explanation of the regex pattern used:

    \S+                        match a key
    \s*                        followed by optional whitespace and
    =                          literal '='
    \s*                        more optional whitespace
    .*?                        match anything until seeing
    (?=\s*,\s*\S+\s*=|\s*\}$)  that what follows is either the start of the next key/value OR
                               is the end of the input