0

大家好,我正在将文件读入字符串变量,但是我想知道将字符串中的特定元素仅返回到新变量中的最佳方法是什么。

我有以下字符串数据文件:

[TEST1]
mem.consumed.average = 965608688
cpu.usagemhz.average = 18653
Hosts = 3
Points = 1535
RAM = 1535.96
CPU = 191.79
Powered_on VMs = 70
Powered_on RAM = 1049.02
Powered_on CPU = 410.15
Powered_on Points = 1051
Provisioned VMs = 74
Provisioned RAM = 1057.02
Provisioned CPU = 416.59
Provisioned Points = 1059

[TEST2]
mem.consumed.average = 298762549
cpu.usagemhz.average = 7782
Hosts = 4
Points = 1535
RAM = 1535.96
CPU = 191.79
Powered_on VMs = 54
Powered_on RAM = 303.00
Powered_on CPU = 266.29
Powered_on Points = 303
Provisioned VMs = 60
Provisioned RAM = 330.00
Provisioned CPU = 295.28
Provisioned Points = 330

我只想返回“Hosts”的值,所以在上面的例子中只有 Hosts = 3(来自 [TEST1])和 Hosts = 4(来自 [TEST2])。任何想法将不胜感激:)

4

3 回答 3

1

使用正则表达式类。

http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx

于 2012-04-24T16:40:58.857 回答
1

我会逐行阅读并寻找line.StartsWith("Hosts")-如果是这样,请取出您需要的内容。

于 2012-04-24T16:36:00.437 回答
0

如果您只想将其作为字符串进行搜索,为什么不使用 .indexOf 函数。

所以它会是

int a = data.indexOf('hosts');
int b = data.indexOf('points');

然后

string hosts data = data.Substring(a,b);

您将不得不更改索引以获取确切的值,但这应该很容易,例如

string hosts data = data.Substring(a + 7,b - 2);
于 2012-04-24T16:40:05.073 回答