具有多个分隔符的条件拆分字符串

本文关键字:条件 拆分 字符串 分隔符 | 更新日期: 2023-09-27 18:26:38

我有一个字符串

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

我想根据分隔符来分隔这个字符串。如果我在开头有#,这将指示Section字符串(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-通过多字符分隔符但这不是我想要做的。

具有多个分隔符的条件拆分字符串

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();

带字符串。拆分您可以这样做(比regex更快;)

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));
}