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 但这不是我想要做的。

4

2 回答 2

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();
于 2013-08-06T10:21:56.560 回答
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));
}
于 2013-08-06T10:21:33.910 回答