2009-06-23 25 views
1

我有一个字符串数组和值如下如何从格式化的字符串中提取值?

sNames[0] = "Root | [<root>] | [ID = 1]"; 
sNames[1] = "Planning | [Root] | [ID = 2]"; 

从这个我想只提取ID值.. 1,2 ..

现在是这样做的:

foreach (var s in sNames) 
{ 
    int id = Convert.ToInt32(s.Split('|')[2].Split('=')[1].Substring(1,1)); 
    ... 
} 

还有其他一些好方法吗?

感谢

回答

5

您可以使用正则表达式查找ID(匹配()部分可能不是100%正确的 - 运动留给读者)。

var regex = new Regex(@"\[ID = (?<id>[0-9]+)\]"); 
var ids = sNames.Select(s => Convert.ToInt32(regex.Match(s).Groups["id"].Value)); 
+0

请记住,这将无法在.NET 2.0或3.0下工作,由于要求Linq! – MiffTheFox 2009-06-23 05:42:42

2

您可以使用正则表达式...

// using System.Text.RegularExpressions 
Regex rx = new Regex(@"\[ID\s*=\s*(\d+)\]", RegexOptions.IgnoreCase); 
foreach (var s in sNames) 
{ 
    Match m = rx.Match(s); 
    if (!m.Success) continue; // Couldn't find ID. 
    int id = Convert.ToInt32(m.Groups[1].ToString()); 
    // ... 
} 

now you have two problems。 ;-)

1

正则表达式是“最简单的”。当然,要注意的是正则表达式有一个巨大的学习曲线。

Regex rx = new Regex(@"\[ID\s*=\s*(?<id>\d+)\]"); 
Match m = rx.Match(str); 
string id = m.Groups["id"].Value; 
2

听起来像正规表达式的工作。这将匹配所有字符串的模式“ID = [某个数字]”

using System.Text.RegularExpressions; 
... 

foreach(string s in sNames) { 
    Match m = Regex.Match("ID = ([0-9]+)"); 
    if(m.Success) { 
    int id = Convert.ToInt32(m.Groups[1]); 
    } 
} 
相关问题