从字符串中仅获取某些分组的最佳方法

时间:2010-10-19 03:22:16

标签: c#

我使用以下代码获取文件名列表:

        //Set up Datatable
        dtUpgradeFileInfo.Columns.Add("BaseFW");
        dtUpgradeFileInfo.Columns.Add("ActiveFW");
        dtUpgradeFileInfo.Columns.Add("UpgradeFW");
        dtUpgradeFileInfo.Columns.Add("FileName");

        //Gets Upgrade information and upgrade Files from Upgrade Folder
        DirectoryInfo di = new DirectoryInfo(g_strAppPath + "\\Update Files");
        FileInfo[] rgFiles = di.GetFiles("*.txt");
        foreach (FileInfo fi in rgFiles)
        {
            test1 = fi.Name.ToString();


        }

所有文件名均采用BXXXX_AXXXX_UXXXX格式。当然,X代表0-9的数字,我需要将这3个数字组合在一起,将每个数字放入Datatable中各自的列中。我最初打算获得代表每个分组的字符并将它们放在一起用于每个分组,但我想知道是否有比将其发送到charArray更好的方式/更快的方式。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

这是一种从test1(没有LINQ)中获取数字的相对简单的方法:

...
string test1 = fi.Name.ToString();

int baseFW=0;
int activeFW=0;
int upgradeFW=0;

// Break the file name into the three groups
string[] groups=test1.Split('_');

if (groups.Length==3)
{
  // Create a numbers array to hold the numbers
  int[] nums=new int[groups.Length];

  // Parse the numbers out of the strings
  int idx=0;
  foreach (string s in groups)
    nums[idx++]=int.Parse(s.Remove(0,1)); // Convert to num 

  baseFW=nums[0];
  activeFW=nums[1];
  upgradeFW=nums[2];
}
else
{
  // Error handling...
}

如果您想使用LINQ执行此操作,则更容易:

...
string test1 = fi.Name.ToString();

int baseFW=0;
int activeFW=0;
int upgradeFW=0;

// Extract all numbers
int[] nums=test1.Split('_') // Split on underscores
                .Select(s => int.Parse(s.Remove(0,1))) // Convert to ints
                .ToArray(); // For random access, below

if (nums.Length==3)
{
  baseFW=nums[0];
  activeFW=nums[1];
  upgradeFW=nums[2];
}
else
{
   // Error handling...
}

答案 1 :(得分:2)

使用正则表达式可以轻松解析所需的值,并且还有一个额外的好处,即允许您跳过目录中最终与预期文件名格式不匹配的文件。

您的代码看起来像这样:

        //Gets Upgrade information and upgrade Files from Upgrade Folder 
        string strRegex = @"^B(?<Base>[0-9]{4})_A(?<Active>[0-9]{4})_U(?<Upgrade>[0-9]{4}).txt$";
        RegexOptions myRegexOptions = RegexOptions.ExplicitCapture | RegexOptions.Compiled;
        Regex myRegex = new Regex(strRegex, myRegexOptions);

        DirectoryInfo di = new DirectoryInfo(g_strAppPath + "\\Update Files");
        FileInfo[] rgFiles = di.GetFiles("*.txt");
        foreach (FileInfo fi in rgFiles)
        {
            string name = fi.Name.ToString();
            Match matched = myRegex.Match(name);
            if (matched.Success)
            {
                //do the inserts into the data table here
                string baseFw = matched.Groups["Base"].Value;
                string activeFw = matched.Groups["Active"].Value;
                string upgradeFw = matched.Groups["Upgrade"].Value;
            }
        }