Split string by commas ignoring any punctuation marks (including ',') in quotation marks

前端 未结 6 1759
甜味超标
甜味超标 2021-01-22 06:10

How can I split string (from a textbox) by commas excluding those in double quotation marks (without getting rid of the quotation marks), along with other poss

6条回答
  •  不要未来只要你来
    2021-01-22 06:22

    You could try the below regex which uses positive lookahead,

    string value = @"apple, orange, ""baboons, cows"", rainbow, ""unicorns, gummy bears""";
    string[] lines = Regex.Split(value, @", (?=(?:""[^""]*?(?: [^""]*)*))|, (?=[^"",]+(?:,|$))");
    
    foreach (string line in lines) {
    Console.WriteLine(line);
    }
    

    Output:

    apple
    orange
    "baboons, cows"
    rainbow
    "unicorns, gummy bears"
    

    IDEONE

提交回复
热议问题