c# - C#中的解析树

标签 c# parsing tree

我有一个像这样的[文本]树:

+---step-1
|   +---step_2
|   |   +---step3
|   |   \---step4
|   +---step_2.1
|   \---step_2.2
+---step1.2

树2

+---step-1
|   \---step_2
|   |   +---step3
|   |   \---step4
+---step1.2

这只是一个小例子,树可以更深,有更多的 child 等等。

现在我正在这样做:

for (int i = 0; i < cmdOutList.Count; i++)
{
    string s = cmdOutList[i];
    String value = Regex.Match(s, @"(?<=\---).*").Value;
    value = value.Replace("\r", "");
    if (s[1].ToString() == "-")
    {
        DirectoryNode p = new DirectoryNode { Name = value };
        //p.AddChild(f);
        directoryList.Add(p);
    }
    else
    {
        DirectoryNode f = new DirectoryNode { Name = value };
        directoryList[i - 1].AddChild(f);
        directoryList.Add(f);
    }
}

但这不处理“step_2.1”和“step_2.2”

我认为我这样做是完全错误的,也许有人可以帮我解决这个问题。

编辑:

这里是 DirectoryNode 类,使它更清楚一点..

public class DirectoryNode
{
    public DirectoryNode()
    {
        this.Children = new List<DirectoryNode>();
    }
    public DirectoryNode ParentObject { get; set; }
    public string Name;
    public List<DirectoryNode> Children { get; set; }

    public void AddChild(DirectoryNode child)
    {
        child.ParentObject = this;
        this.Children.Add(child);
    }
}

最佳答案

如果您的文本很简单(只是 +---\--- 前面有一系列 |),那么正则表达式可能超出您的需要(以及什么让您感到困惑)。

DirectoryNode currentParent = null;
DirectoryNode current = null;
int lastStartIndex = 0;

foreach(string temp in cmdOutList)
{
    string line = temp;

    int startIndex = Math.Max(line.IndexOf("+"), line.IndexOf(@"\");

    line = line.Substring(startIndex);

    if(startIndex > lastStartIndex) 
    {
        currentParent = current;
    }
    else if(startIndex < lastStartIndex)
    {
        for(int i = 0; i < (lastStartIndex - startIndex) / 4; i++)
        {
            if(currentParent == null) break;

            currentParent = currentParent.ParentObject;
        }
    }

    lastStartIndex = startIndex;

    current = new DirectoryNode() { Name = line.Substring(4) };

    if(currentParent != null)
    {
        currentParent.AddChild(current);
    }
    else
    {
        directoryList.Add(current);
    }
}

关于c# - C#中的解析树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4958701/

相关文章:

c# - 如何在 VS 2010 中添加 microsoft.office.interop.word(2003 版)

c# - 将文本文件写入子文件夹

c - 如何处理用于两件事的相同符号柠檬解析器

excel - VBA XML : Find root nodes for multiple namespaces

c - C语言中的红黑树

gwt : drag n drop tree

c# - 如何在使用 JSON.Net 序列化期间有条件地忽略字段和属性?

c# - Web异常: The request was aborted: Could not create SSL/TLS secure channel

C# : delete repetitive character

algorithm - 是否可以设计一棵节点有无限多个子节点的树?