Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 681
user1875195 Avatar asked Mar 14 '13 22:03

user1875195


People also ask

How do I split a string into another string?

Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.

What is splitting a string?

String splitting is the process of breaking up a text string in a systematic way so that the individual parts of the text can be processed. For example, a timestamp could be broken up into hours, minutes, and seconds so that those values can be used in the numeric analysis.

What is strtok function in C?

Apr 07, 2007. The C function strtok() is a string tokenization function that takes two arguments: an initial string to be parsed and a const -qualified character delimiter. It returns a pointer to the first character of a token or to a null pointer if there is no token.


1 Answers

Use the Regex.Matches method instead:

string[] result =
  Regex.Matches(str, @"\[.*?\]").Cast<Match>().Select(m => m.Value).ToArray();
like image 158
Guffa Avatar answered Nov 07 '22 22:11

Guffa