Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 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 Reply

0 votes
by (71.8m points)

Use the Regex.Matches method instead:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...