Parse string with whitespace and quotation mark (with quotation mark retained)

前端 未结 3 1210
心在旅途
心在旅途 2020-12-11 04:42

If I have a string like this

create myclass \"56, \'for the better or worse\', 54.781\"

How can I parse it such that the resul

3条回答
  •  天命终不由人
    2020-12-11 05:39

    I would use a real csv-parser for this task. The only one available in the framework is the TextFieldParser-class in the VisualBasic namespace:

    string str = "create myclass \"56, 'for the better or worse', 54.781\"";
    var allLineFields = new List();
    using (var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(new StringReader(str)))
    {
        parser.Delimiters = new string[] { " " };
        parser.HasFieldsEnclosedInQuotes = true;  // important
        string[] lineFields;
        while ((lineFields = parser.ReadFields()) != null)
        {
            allLineFields.Add(lineFields);
        }
    }
    

    Result:

    But there are others available like this or this.

提交回复
热议问题