从字符串中提取两个子字符串

时间:2013-03-26 15:34:52

标签: c#

从指定字符串中提取子字符串的最佳和优化方法是什么。

我的主要字符串就像

string str = "<ABCMSG><t>ACK</t><t>AAA0</t><t>BBBB1</t></ABCMSG>"; 

其中值AAA0BBBB1不是常量。它是从某个地方收集的动态值。

我需要在这里提取AAA0和BBBB1。

如果有任何功能或优化方式,请建议我。

谢谢你!

1 个答案:

答案 0 :(得分:2)

string str = @"<ABCMSG><t>ACK</t><t>AAA0</t><t>BBBB1</t></ABCMSG>";
var matches = Regex.Matches(str, @"<t>(\w+)<\/t>");

Console.WriteLine(matches[1].Groups[1]);    // outputs "AAAA1"
Console.WriteLine(matches[2].Groups[1]);    // outputs "BBB2"

这假设您的数据始终位于<t></t>标记内,如果找不到匹配项,您可能还希望执行一些错误捕获。

相关问题