user1875195
user1875195

Reputation: 988

Splitting a string in C#

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!

Upvotes: 17

Views: 61962

Answers (4)

p.s.w.g
p.s.w.g

Reputation: 149108

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

Upvotes: 20

Kenneth K.
Kenneth K.

Reputation: 3039

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.

Upvotes: 2

Brian Surowiec
Brian Surowiec

Reputation: 17301

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.

Upvotes: 1

Guffa
Guffa

Reputation: 700910

Use the Regex.Matches method instead:

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

Upvotes: 28

Related Questions