Splitting a string in C#

后端 未结 4 1922
北恋
北恋 2020-12-06 17:40

I am trying to split a string in C# the following way:

Incoming string is in the form

string str = \"[message details in here][another message here]/         


        
相关标签:
4条回答
  • 2020-12-06 17:44

    The Split method returns sub strings between the instances of the pattern specified. For example:

    var items = Regex.Split("this is a test", @"\s");
    

    Results in the array [ "this", "is", "a", "test" ].

    The solution is to use Matches instead.

    var matches =  Regex.Matches(str, @"\[[^[]+\]");
    

    You can then use Linq to easily get an array of matched values:

    var split = matches.Cast<Match>()
                       .Select(m => m.Value)
                       .ToArray();
    
    0 讨论(0)
  • 2020-12-06 17:52

    Use the Regex.Matches method instead:

    string[] result =
      Regex.Matches(str, @"\[.*?\]").Cast<Match>().Select(m => m.Value).ToArray();
    
    0 讨论(0)
  • 2020-12-06 18:01

    Instead of using a regex you could use the Split method on the string like so

    Split(new[] { '\n', '[', ']' }, StringSplitOptions.RemoveEmptyEntries)
    

    You'll loose [ and ] around your results with this method but it's not hard to add them back in as needed.

    0 讨论(0)
  • 2020-12-06 18:02

    Another option would be to use lookaround assertions for your splitting.

    e.g.

    string[] split = Regex.Split(str, @"(?<=\])(?=\[)");
    

    This approach effectively splits on the void between a closing and opening square bracket.

    0 讨论(0)
提交回复
热议问题