Split a string that has white spaces, unless they are enclosed within “quotes”?

后端 未结 7 701
无人共我
无人共我 2020-11-30 00:12

To make things simple:

string streamR = sr.ReadLine();  // sr.Readline results in:
                                 //                         one \"two two\         


        
相关标签:
7条回答
  • 2020-11-30 01:11

    With support for double quotes.

    String:

    a "b b" "c ""c"" c"
    

    Result:

    a 
    "b b"
    "c ""c"" c"
    

    Code:

    var list=Regex.Matches(value, @"\""(\""\""|[^\""])+\""|[^ ]+", 
        RegexOptions.ExplicitCapture)
                .Cast<Match>()
                .Select(m => m.Value)
                .ToList();
    

    Optional remove double quotes:

    Select(m => m.StartsWith("\"") ? m.Substring(1, m.Length - 2).Replace("\"\"", "\"") : m)
    

    Result

    a 
    b b
    c "c" c
    
    0 讨论(0)
提交回复
热议问题