C#人类可读性的特殊语法



嗨,我有点需要一些帮助,以创建一个以人类可读格式转动普通语法的函数:

语法看起来像这样:

[OPENTAG]
(type)name:value
[OPENTAG]
(type)name:value
(type)name:value
(type)name:value
[/CLOSETAG]
[/CLOSETAG]

想将其转变为:

    [Opentag]         (类型)名称:值         [Opentag]             (类型)名称:值             (类型)名称:值             (类型)名称:值         [/clesetag]    [/clesetag]
    private string textFormater(string input)
    {
        string[] lines = Regex.Split(input, "rn");
        int tabs = 0;
        string newtext = "";
        foreach (string line in lines)
        {
            Match m = Regex.Match(line, "\[.*\]");
            bool isTop;
            bool isTopClose = false;
            string tabtext = "";
            if (m.Success)
            {
                if (line.Contains("/"))
                {
                    tabs--;
                    isTopClose = true;
                }
                else
                {
                    tabs++;
                }
                isTop = true;
            }
            else
            {
                isTop = false;
            }
            if (isTop && !isTopClose && tabs == 1)
            {
                newtext += line;
            }
            else if (isTop && !isTopClose)
            {
                for (int i = 1; i <= tabs - 1; i++)
                {
                    tabtext += "t";
                }
                newtext += "rn" + tabtext + line;
            }
            else
            {
                for (int i = 1; i <= tabs; i++)
                {
                    tabtext += "t";
                }
                newtext += "rn" + tabtext + line;
            }
        }
        return newtext;
    }

我有ATM一个解决方案,但是代码是如此杂乱而缓慢,在2MB文件中,需要年龄的时间:)感谢您的帮助!

欢呼

尝试将StringBuilder用于输出文本而不是仅仅是字符串,这应该加快速度。

编辑:

这可以做您想要的吗?

private static string textFormater2(string input)
    {
        string[] lines = Regex.Split(input, "rn");
        int tabCount = 0;
        StringBuilder output = new StringBuilder();
        using (StringReader sr = new StringReader(input))
        {
            string l;
            while (!string.IsNullOrEmpty(l = sr.ReadLine()))
            {
                if (l.Substring(0, 1) == "[")
                    if (l.Contains('/'))
                        tabCount--;
                string tabs = string.Empty;
                for (int i = 0; i < tabCount; i++)
                    tabs += "t";
                output.AppendLine(tabs + l);
                if (l.Substring(0, 1) == "[")
                    if (!l.Contains('/'))
                        tabCount++;
            }
        }
        return output.ToString();
    }

最新更新