拆分C​​#中的字符串 [英] Splitting a string in C#

查看:103
本文介绍了拆分C​​#中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C#中分割字符串方式如下:

I am trying to split a string in C# the following way:

传入字符串形式

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!

推荐答案

使用 Regex.Matches 方法,而不是:

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

这篇关于拆分C​​#中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆