2

I have a String

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

I want to separate this string according to delimiters. If I have # at the start this will indicate Section string (string[] section). If the string will starts with * this will indicate that I have a category(string[] category). As a result I want to have

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

I have found this answer: string.split - by multiple character delimiter But it is not what I am trying to do.

Community
  • 1
  • 1
focus
  • 171
  • 9
  • 31

2 Answers2

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();
Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92
0

With string.Split You could do this (faster than the 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));
}
lordkain
  • 3,061
  • 1
  • 13
  • 18