Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

regex - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the Regex.Matches method instead:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...