2013-08-06 59 views
2

我有一個字符串條件性拆分字符串分隔符多

string astring="#This is a Section*This is the first category*This is the 
second Category# This is another Section"; 

我想根據定界符這個字符串分開。如果我在開始時有#這將表明部分字符串(字符串[]部分)。如果字符串將以*開頭,則表明我有一個類別(字符串[]類別)。 因此,我想有

string[] section = { "This is a Section", "This is another Section" }; 
string[] category = { "This is the first category ", 
    "This is the second Category " }; 

我發現這個答案: string.split - by multiple character delimiter 但它不是我想做的事。

+2

看起來像一個正則表達式來我一份工作,使用捕獲組,這應該是在散步公園 –

+1

@SimonRapilly你甚至不需要捕獲組。火柴足夠了。 –

+1

如果你的答案有兩個正則表達式,但如果你想要一個正則表達式,那麼你將需要捕獲組 –

回答

2
string [email protected]"#This is a Section*This is the first category*This is the second Category# This is another Section"; 

string[] sections = Regex.Matches(astring, @"#([^\*#]*)").Cast<Match>() 
    .Select(m => m.Groups[1].Value).ToArray(); 
string[] categories = Regex.Matches(astring, @"\*([^\*#]*)").Cast<Match>() 
    .Select(m => m.Groups[1].Value).ToArray(); 
+0

謝謝你的出色解決方案 – focus

0

隨着string.Split你可以這樣做(除了正則表達式更快;))

List<string> sectionsResult = new List<string>(); 
List<string> categorysResult = new List<string>(); 
string astring="#This is a Section*This is the first category*This is thesecond Category# This is another Section"; 

var sections = astring.Split('#').Where(i=> !String.IsNullOrEmpty(i)); 

foreach (var section in sections) 
{ 
    var sectieandcategorys = section.Split('*'); 
    sectionsResult.Add(sectieandcategorys.First()); 
    categorysResult.AddRange(sectieandcategorys.Skip(1)); 
} 
+0

我收到一個錯誤「字符串不包含定義拆分」 – focus

+0

更新示例。 – lordkain