在这种情况下,我需要从一般模式为 [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/