Splitting a string and ignoring the delimiter inside quotes

前端 未结 4 1381
轻奢々
轻奢々 2021-02-19 10:48

I am using .NET\'s String.Split method to break up a string using commas, but I want to ignore strings enclosed in double quotes for the string. I have read that a

For

4条回答
  •  粉色の甜心
    2021-02-19 11:24

    I found below is the easiest way, we can do it

    string fruits = "Fruit,10,"Bananas, Oranges, Grapes"";
    string[] fruitsArr = Regex.Split(fruits, ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
    

    Output:

    fruitsArr[0] = "Fruit"
    fruitsArr[1] = "10"
    fruitsArr[2] = "\"Bananas, Oranges, Grapes\""
    

    If you need pure string data so you can do it something like,

    fruitsArr[2].Replace("\"", "")

提交回复
热议问题