c# - 解析 C Sharp 中的嵌套文本

标签 c# parsing text-parsing

如果我有一系列具有此基本格式的字符串:

"[id value]"//id and value are space delimited.  id will never have spaces

然后它们可以像这样嵌套:

[a]
[a [b value]]
[a [b [c [value]]]

因此每个项目可以有 0 或 1 个值条目。

解析这种格式的最佳方法是什么?我只使用 string.Split() 或 string.IndexOf() 这样的东西还是有更好的方法?

最佳答案

split和indexof方法没有任何问题,它们是为了字符串解析而存在的。 以下是您的案例的示例:

        string str = "[a [b [c [d value]]]]";

        while (str.Trim().Length > 0)
        {
            int start = str.LastIndexOf('[');
            int end = str.IndexOf(']');

            string s = str.Substring(start +1, end - (start+1)).Trim();
            string[] pair = s.Split(' ');// this is what you are looking for. its length will be 2 if it has a value

            str = str.Remove(start, (end + 1)- start);
        }

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

相关文章:

parsing - 如何将此语法转换为 LR(1)?

php - 获取非数字字符,然后在文本 block 的每一行上编号

matlab - 从文本文件导入并在 matlab 中创建元胞数组

JavaScript:解析这个字符串

c# - 获取本地照片 Windows Phone 8 模拟器

ios - 根据数据更新rootview Controller

c# - ASP.Net/C# : Replacing characters in a databound field

c++ - 包含由 flex 和 bison 生成的代码

c# - 如何使用 Facebook App 指定 Windows 桌面平台

c# - 如何让 ConfigurationManager 从多个文件加载应用程序设置?