splitting a string based on multiple char delimiters

前端 未结 5 1208
你的背包
你的背包 2020-12-01 11:53

I have a string \"4,6,8\\n9,4\"

I want to split this based on ,and \\n

Output array should be

4
6
8
9
4

Edit :

5条回答
  •  悲哀的现实
    2020-12-01 12:05

    Another option is to use Regex.Split. This is useful when the split sequences are more complex. For instance if spaces can also be part of the split delimiters such as:

    "4,6,8 , 9\\n\\n4"
    

    Then:

    using System.Text.RegularExpressions;
    var i = "4,6,8 , 9\n\n4";
    var o = Regex.Split(i, @"[,\s\n]+");
    // now o is:
    // new string[] { "4", "6", "8", "9" }
    

    Note that the regular expression used is "more accepting" - it ignored the empty "space" between the \n's and it would accept "4 6 8 9 4" just the same - so the above to to show a point: there is more than one way to skin a cat.

    Happy coding.

提交回复
热议问题