如何使用C#仅从文件名中提取日期

时间:2019-05-03 14:44:51

标签: c# regex ssis script-task

我遇到一种情况,我需要从一般模式为[XXXX_BBBB]_YYYY-MM-DD[.fileExtension]例如Sales_person_2019-05-03.xlsx的文件名中提取日期。

我正在SSIS脚本任务组件中使用c#来实现这一目标。

下面是我的代码:

public void Main()
{

            // TODO: Add your code here
   string pat;
   string date;
   string filename = 'Sales_person_2019-05-03.xlsx'

   // Get the Date part from the file name only
   pat = @"[0-9]{2}[0-9]{2}[0-9]{4}";
   Regex r = new Regex(pat, RegexOptions.IgnoreCase);
   date = r.Match(filename);
   MessageBox.Show(date.ToString());}


    Dts.TaskResult = (int)ScriptResults.Success;
}

但是这不起作用。请有人帮忙。 C#上的新手

1 个答案:

答案 0 :(得分:1)

您无需使用正则表达式就可以实现此目的,只需使用字符串函数(IndexOf()Substring())即可:

由于您要处理固定模式[XXXX_BBBB]_YYYY-MM-DD[.fileExtension],因此只需检索第二个下划线后的10个字符即可。

public void Main()
{

    string filename = "Sales_person_2019-05-03.xlsx";

    // Get the Date part from the file name only
    string filedate = filename.Substring(filename.IndexOf('_',filename.IndexOf('_') + 1) + 1,10);

    DateTime dt = DateTime.ParseExact(filedate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None)

    Dts.TaskResult = (int)ScriptResults.Success;
}