Splitting a string in C#

45,285

Solution 1

Use the Regex.Matches method instead:

string[] result =
  Regex.Matches(str, @"\[.*?\]").Cast<Match>().Select(m => m.Value).ToArray();

Solution 2

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();

Solution 3

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.

Share:
45,285
user1875195
Author by

user1875195

Updated on March 15, 2020

Comments

  • user1875195
    user1875195 about 4 years

    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]/n/n[anothermessage here]"
    

    And I am trying to split it into an array of strings in the form

    string[0] = "[message details in here]"
    string[1] = "[another message here]"
    string[2] = "[anothermessage here]"
    

    I was trying to do it in a way such as this

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

    But it does not work correctly this way, I am just getting an empty array or strings

    Any help would be appreciated!

  • p.s.w.g
    p.s.w.g about 11 years
    That will also break on \n between [ and ]. I don't think that's what OP wants
  • Kenneth K.
    Kenneth K. about 11 years
    Did you test your Split example? Aside from not properly escaping the \w, the result you mention is completely wrong.
  • p.s.w.g
    p.s.w.g about 11 years
    @KennethK Thanks. I wrote that edit on my way out the door, and didn't have a chance to proofread it. I fixed it.
  • malik masis
    malik masis almost 2 years
    no need Cast<Match>