2012-01-08 57 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; 
} 
相关问题