如何找到由周围下划线限定的5个数字变量集?

时间:2017-11-07 20:04:13

标签: c# sql-server regex ssis etl

我将文件名拉入变量(@[User::FileName])并尝试从该字符串中提取工单号(两侧始终带有下划线的5个数字)。例如,文件名看起来像 - "ABC_2017_DEF_9_12_GHI_35132_S5160.csv"。我想结果返回“35132”。我找到了如何执行此操作的示例,例如SUBSTRING(FileName,1,FINDSTRING(FileName,"_",1) - 1),但下划线并不总是位于同一位置。

是否可以在表达式构建器中执行此操作?

答案:

public void Main()
{
    string strFilename = Dts.Variables["User::FileName"].Value.ToString();
    var RegexObj = new Regex(@"_([\d]{5})_");
    var match = RegexObj.Match(strFilename);

    if (match.Success)
    {
        Dts.Variables["User::WorkOrder"].Value = match.Groups[1].Value;
    }
    Dts.TaskResult = (int)ScriptResults.Success;
}

3 个答案:

答案 0 :(得分:2)

首先,您提供的示例ABC_2017_DEF_9_12_GHI_35132_S5160.csv包含位于下划线之间的4个数字:

2017 , 9 , 12 , 35132

我不知道文件名是否包含多个5位数字可能会多次出现,所以在我的回答中我会假设你想要返回的号码是5位数字的最后一次出现

解决方案

您必须使用以下正则表达式:

(?:_)\K[0-9][0-9][0-9][0-9][0-9](?=_)  

DEMO

@MartinSmith建议的(在评论中),您可以使用以下RegEx:

_([\d]{5})_

在SSIS中实施RegEx

  1. 首先添加另一个变量(例如:@[User::FileNumber]
  2. 添加脚本任务,选择@[User::Filename]变量作为ReadOnlyVariable,@[User:FileNumber]作为ReadWriteVariable
  3. 在脚本任务中使用以下代码:

    using System.Text.RegularExpressions;
    
    public void Main()
    {
    
        string strFilename = Dts.Variables["filename"].Value.ToString();
        string strNumber;
        var objRegEx = new Regex(@"(?:_)\K[0-9][0-9][0-9][0-9][0-9](?=_)");
        var mc = objRegEx.Matches(strFilename);
    
    
        //The last match contains the value needed
        strNumber = mc[mc.Count - 1].Value;
    
    
        Dts.Variables["FileNumber"].Value.ToString();
    
        Dts.TaskResult = (int)ScriptResults.Success;
    }
    

答案 1 :(得分:1)

其他部分意味着什么?

无论如何,您可以使用脚本任务和拆分功能。

将@fileName作为readonly传递,将@WO作为readwrite传递

string fn = Dts.Variables["fileName"].Value; 
string[] parts = fn.Split('_');

//Assuming it's always the 7th part 
// You could extract the other    parts as well. 
Dts.Variables["WO"].Value = part(6);

答案 2 :(得分:0)

我会使用脚本转换(或脚本任务,如果这不在DataFlow中)并使用正则表达式。