带有多个分隔符的条件分割字符串

时间:2013-08-06 10:06:11

标签: c# asp.net string delimiter

我有一个字符串

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

我想根据分隔符分隔这个字符串。如果我在开头有#,则表示Section string(string [] section)。如果字符串将以*开头,则表示我有一个类别(string []类别)。 结果我想拥有

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 个答案:

答案 0 :(得分:2)

string astring=@"#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();

答案 1 :(得分: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));
}