您可以使用递归算法来分析您的字符串像这样:
static IEnumerable<Item> Parse(string source)
{
var root = new Item() { Name = "Root", Children = new List<Item>() };
AddChildrenTo(root, source);
return root.Children;
}
static int AddChildrenTo(Item item, string source)
{
Item node = null;
var word = new List<char>();
for (int i = 0; i < source.Length; i++)
{
var c = source[i];
if (new[] { ',', '(', ')' }.Contains(c))
{
if (word.Count > 0)
{
node = new Item { Name = new string(word.ToArray()), Children = new List<Item>() };
(item.Children as List<Item>).Add(node);
word.Clear();
}
if (c == '(')
{
i += AddChildrenTo(node, source.Substring(i + 1)) + 1;
}
else if (c == ')')
{
return i;
}
}
else if (char.IsLetter(c)) // add other valid characters to if condition
{
word.Add(c);
}
}
return source.Length;
}
然后,你可以简单地调用Parse()
(为了更好的示范,我在你的字符串改变了字母(A,B,..)字(柜,书,...)):
string source = "ark,book(cook,door(euro,fun),good),hello,ink(jack,kill,loop)";
var res = Parse(source);
请注意对于一个非常大的字符串递归方法不是最好的解决方案。为了简单起见,我没有做错误检查。
就性能而言,由于C#是一种编译语言,如果您编写自己的解析器(无正则表达式),您将获得最佳结果。 –
您能否为此列表显示一个示例输出? –
孩子的平面列表,还是基于parthentical结构嵌套? – lintmouse