2012-01-08 33 views
0

給出下面的文本文件:保存文件名和HEADERTEXT值作爲鍵值對集合

Find all "HeaderText="", Subfolders, Find Results 1, "Entire Solution" 
    C:\Documents and Settings\user\My Documents\Visual Studio 2008\Projects\WebApplication1\WebApplication1\Default.aspx(16):    <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" 
    C:\Documents and Settings\user\My Documents\Visual Studio 2008\Projects\WebApplication1\WebApplication1\Default.aspx(18):    <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" 
    C:\Documents and Settings\user\My Documents\Visual Studio 2008\Projects\WebApplication1\WebApplication1\Default.aspx(20):    <asp:BoundField DataField="ContactName" HeaderText="ContactName" 
    Matching lines: 3 Matching files: 1 Total files searched: 5 

什麼把剛纔的文件名和的HeaderText的集合中值的最佳方法?

for example, 

var test = new List<KeyValuePair<string,string>>(); 

test.Add(Default.aspx, CustomerID); 
test.Add(Default.aspx, CompanyName); 
test.Add(Default.aspx, ContactName); 

回答

0

你可以使用正則表達式:

public IEnumerable<KeyValuePair<string, string>> Parse(StreamReader reader) 
{ 
    string line; 
    while ((line = reader.ReadLine()) != null) 
    { 
     var tokens = Regex.Split(line, @"\(\d+\)\:"); 
     if (tokens.Length > 1) 
     { 
      var file = Path.GetFileName(tokens[0]); 
      var match = Regex.Match(tokens[1], @"HeaderText=\""(\w+)\"""); 
      if (match.Success) 
      { 
       yield return new KeyValuePair<string, string>(
        file, match.Groups[1].Value 
       ); 
      } 
     } 
    } 
} 

可稱爲是這樣的:

using (var reader = File.OpenText("test.txt")) 
{ 
    foreach (var item in Parse(reader)) 
    { 
     Console.WriteLine("file: {0}, header: {1}", item.Key, item.Value); 
    } 
} 
+0

只是用Visual Studio進行測試,發現一個nd使用正則表達式選項替換(Ctrl + Shft + H)我嘗試粘貼「HeaderText = \」「(\ w +)\」「但它沒有找到任何東西?應該有3個結果 – Rod 2012-01-08 18:34:55

1

我會建議NameValueCollection而不是List<KeyValuePair<string,string>>來保持你的配對。 NameValueCollection每個密鑰可以有多個條目。

如果文件不是非常大,你可以做到以下幾點:

  1. 使用System.IO.File.ReadAllLines閱讀文件並執行 在陣列中的每個有效行步驟2-4。

  2. 使用Path.GetFileName從完整路徑獲取文件名。

  3. 使用IndexOfSubstring解析字符串以獲取 HeaderText值。

  4. 將這一對添加到NameValueCollection

1

另一個正則表達式的解決方案,這一個用途命名組:

public static List<KeyValuePair<string, string>> Process(string fileContents) 
{ 
    const string regexPattern = @"\\(?<filename>[\w\.]+)\(.*HeaderText=""(?<headerText>\w+)"""; 

    var matches = Regex.Matches(fileContents, regexPattern); 

    var test = new List<KeyValuePair<string, string>>(); 

    foreach (Match match in matches) 
    { 
     var fileName = match.Groups["filename"].Value; 
     var headerText = match.Groups["headerText"].Value; 

     test.Add(new KeyValuePair<string, string>(fileName, headerText)); 
    } 

    return test; 
}