2013-03-14 70 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, @"(?<=\])(?=\[)"); 

這種方法有效地分裂了閉合和開放方括號之間的空隙。