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

前端 未结 6 1715
甜味超标
甜味超标 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:34

    Much like a CSV parser, instead of Regex, you can loop through each character, like so:

    public List ItemStringToList(string inputString)
    {  
        var itemList   = new List();
        var currentIem = "";
        var quotesOpen = false;
    
        for (int i = 0; i < inputString.Length; i++)
        {
            if (inputString[i] == '"')
            {
                quotesOpen = !quotesOpen;
                continue;
            }
    
            if (inputString[i] == ',' && !quotesOpen)
            {
                itemList.Add(currentIem);
                currentIem = "";
                continue;
            }
    
            if (currentIem == "" && inputString[i] == ' ') continue;
            currentIem += inputString[i];
        }
    
        if (currentIem != "") itemList.Add(currentIem);
    
        return itemList;
    }
    

    Example test usage:

    var test1 = ItemStringToList("one, two, three");
    var test2 = ItemStringToList("one, \"two\", three");
    var test3 = ItemStringToList("one, \"two, three\"");
    var test4 = ItemStringToList("one, \"two, three\", four, \"five six\", seven");
    var test5 = ItemStringToList("one, \"two, three\", four, \"five six\", seven");
    var test6 = ItemStringToList("one, \"two, three\", four, \"five six, seven\"");
    var test7 = ItemStringToList("\"one, two, three\", four, \"five six, seven\"");
    

    You could change it to use StringBuilder if you want faster character joining.

提交回复
热议问题