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

前端 未结 3 1206
心在旅途
心在旅途 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:22

    Regex Demo

    (\w+|"[^"]*")
    

    Get the matches in the first capture group.

    1. \w+: Matches alphanumeric characters and underscore one or more times
    2. "[^"]*": Matches anything that is wrapped in double quotes
    3. |: OR condition in regex
    0 讨论(0)
  • 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<string[]>();
    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.

    0 讨论(0)
  • 2020-12-11 05:48

    You can split by this

    \s(?=(?:[^"]*"[^"]*")*[^"]*$)
    

    See demo.

    https://regex101.com/r/fM9lY3/60

    string strRegex = @"\s(?=(?:[^""]*""[^""]*"")*[^""]*$)";
    Regex myRegex = new Regex(strRegex, RegexOptions.Multiline);
    string strTargetString = @"create myclass ""56, 'for the better or worse', 54.781""";
    
    return myRegex.Split(strTargetString);
    
    0 讨论(0)
提交回复
热议问题