2

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

"[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() 之类的东西,还是有更好的方法?

4

4 回答 4

2

一点递归和拆分就可以了,重点是使用递归,它会让事情变得容易得多。您的输入语法看起来有点像 LISP :)

Parsing a, split, no second part. done.
Parsing a [b value]. has second part, go to the beginning.
...

你明白了。

于 2010-10-12T07:33:06.360 回答
2

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);
        }
于 2010-10-12T08:39:13.127 回答
1

正则表达式总是一个不错的解决方案。

string test = "[a [b [c [value]]]";
Regex r = new Regex("\\[(?<id>[A-Za-z]*) (?<value>.*)\\]");
var res = r.Match(test);

然后您可以获取该值(第一次迭代后为 [b [c [value]] )并再次应用相同的值,直到匹配失败。

string id = res.Groups[1].Value;
string value = res.Groups[2].Value;
于 2010-10-12T07:38:02.247 回答
0

简单的拆分应该工作对于每个id,都有一个括号[
因此,当您拆分该字符串时,您有n 个括号,因此最后一个元素包含该值的n-1 个id(s)。

于 2010-10-12T07:35:20.363 回答