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

标签 c# regex ssis etl 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# 新手

最佳答案

无需正则表达式即可实现此目的,只需使用字符串函数(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;
}

关于c# - 如何使用 C# 仅从文件名中提取日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55972164/

相关文章:

sql - SSIS 部署 : SSIS Package run time error in SQL Server deployment

c# - 使用 openxml SDK 从 Word 文档中提取字段值

c# - 使用 linq 从 var 中提取一列

regex - 如何在 Perl 中用不同的随机值多次替换同一个字符串?

javascript - 用于至少一个字母表 (A-z) 的名称验证的正则表达式

sql-server-2005 - SSIS 2005 : "Append rows to the destination table" is greyed out. 为什么?

c# - 组织扩展方法

c# - 获取从计算机到手机的通知

c++ - Perl 正则表达式运行速度快于 C++ Boost 实现

ssis - 事实表核对或验证