C # line splitting

I am trying to split a string in C # as follows:

The incoming line is in the form

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

And I'm 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 tried to do it in a way like this

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

But this does not work correctly, I just get an empty array or strings

Any help would be appreciated!

+7
source share
4 answers

Use Regex.Matches :

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

The Split method returns substrings between instances of the specified template. For example:

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

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

The solution is to use Matches instead.

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

Then you can use Linq to easily get an array of matching values:

 var split = matches.Cast<Match>() .Select(m => m.Value) .ToArray(); 
+9
source

Another option would be to use lookaround statements for your separation.

eg.

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

This approach effectively breaks into the void between the square bracket of closing and opening.

0
source

Instead of using a regular expression, you can use the Split method for a string, for example:

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

You will lose [ and ] around your results using this method, but it’s not difficult to add them if necessary.

-one
source

All Articles