2009-06-23 77 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]); 
    } 
} 
相關問題