I would like to split the string below by using regex expression
Country:Subdivision, Level1:{Level2a:{Level3a, Level3b}, Level2b}
into form of
Country
Subdivision
Level1
Level2a
Level3a
Level3b
Level2b
I knew there will be a recursive function to split to string into the above form.
I'm using .net, and want to split to string into a class
public class ListHierarchy
{
public string Name { get; set; }
public ListHierarchy ParentListHierarchy { get; set; }
}
The concept as below (Output):
var list1 = new ListHierarchy() { Name = "Country" };
var list2 = new ListHierarchy() { Name = "Subdivision", ParentListHierarchy = list1 };
var list3 = new ListHierarchy() { Name = "Level1" };
var list4 = new ListHierarchy() { Name = "Level2a", ParentListHierarchy = list3 };
var list5 = new ListHierarchy() { Name = "Level2b", ParentListHierarchy = list3 };
var list6 = new ListHierarchy() { Name = "Level3a", ParentListHierarchy = list4 };
var list7 = new ListHierarchy() { Name = "Level3b", ParentListHierarchy = list4 };
Guys, I have to solution already, but still need to fine tune on the regex
public static Dictionary<string, string> SplitToDictionary(string input, string regexString)
{
Regex regex = new Regex(regexString);
return regex.Matches(input).Cast<Match>().ToDictionary(x => x.Groups[1].Value.Trim(), x => x.Groups[2].Value.Trim());
}
string input = "Country:Subdivision, Level1:{Level2a:{Level3a:Level4a, Level3b}, Level2b}";
var listHierarchy = new List<ListHierarchy>();
Dictionary<string, string> listParent = SplitToDictionary(input, @"([\w\s]+):(([\w\s]+)|([\w\s\,\{\}\:]+))");
but, i getting
{Level2a:{Level3a, Level3b}, Level2b}
rather than
Level2a:{Level3a, Level3b}, Level2b