2013-03-14 72 views
7

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

传入字符串形式

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

,我试图把它分割成一个字符串数组形式

string[0] = "[message details in here]" 
string[1] = "[another message here]" 
string[2] = "[anothermessage here]" 

我试图做到这一点的方式,如本

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

但它不能正常工作这种方式,我只是得到一个空的数组或字符串

任何帮助,将不胜感激!

+7

'但它不能正常工作这种方式 - 请具体。你是什​​么意思?它会抛出异常吗?它不会产生预期的结果吗?如果是这样,它会产生什么?你可以发布吗?请正确地问你的问题,否则你会在这里迅速收到投票并结束投票。 – 2013-03-14 22:48:21

+0

使用字符串类的Split()方法重载之一。 – 2013-03-14 22:49:15

+0

用空字符串替换所有换行符,然后拆分“] [”。 – 2013-03-14 22:49:58

回答

15

使用Regex.Matches方法代替:

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

Split方法返回指定模式的实例之间的子字符串。例如:

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

结果在数组[ "this", "is", "a", "test" ]

解决方法是使用Matches代替。

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

然后,您可以使用LINQ轻松获得匹配值的数组:

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

你测试过你的'Split'例子吗?除了没有正确地转义'\ w',你提到的结果是完全错误的。 – 2013-03-15 00:13:44

+0

@KennethK谢谢。我在出门时编辑了这个编辑,没有机会对它进行校对。我修好了它。 – 2013-03-15 00:28:04

-1

而不是使用正则表达式,你可以使用Split方法就像这样的字符串

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

您将用此方法将结果放在[]附近,但根据需要重新添加它们并不难。

+0

这也会在'['和']''之间的'\ n'上出现。我不认为这是OP想要的 – 2013-03-14 22:57:08

0

另一种选择是使用lookaround断言进行拆分。

例如

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

这种方法有效地分裂了闭合和开放方括号之间的空隙。