如何在C#中重新使用正则表达式变量?

问题描述 投票:0回答:1

是否有一种方法可以覆盖类型为Regex的变量的值?

我有如下工作代码:

string[] dirEntries = Directory.GetFiles(inputDir, "*.csv", SearchOption.TopDirectoryOnly);
var fileList = dirEntries
   .Select(x => new FileMetaDto 
      {
         FileName = Path.GetFileName(x),
         FullPath = x,
         FileType = fileType,
      });
switch (fileType)
  {
  case "pd":  // probability of default
    Regex myRegexPD = new Regex("^PD_");
    fileList = fileList.Where(x => myRegexPD.IsMatch(x.FileName));
    break;
  case "fx":  // exchange rate
    Regex myRegexFx = new Regex("^FX_");
    fileList = fileList.Where(x => myRegexFx.IsMatch(x.FileName));
    break;
  default:
    System.Diagnostics.Debug.WriteLine("File type not valid.");
    break;
}

实际上,此switch语句要长得多,所以我想通过执行以下操作来缩短时间:

my Regex myRegex = new Regex();
switch (fileType)
  {
  case "pd":
    myRegex = "^PD_";
    break;
  case "fx":
    myRegexFx = "^FX_";
    break;
  default:
    System.Diagnostics.Debug.WriteLine("File type not valid.");
    myRegEx = "*";
    break;
}
fileList = fileList.Where(x => myRegex.IsMatch(x.FileName));

但是,这会产生各种类型转换错误。任何建议如何解决这个问题?

参考

c# regex switch-statement
1个回答
1
投票

将模式存储为字符串:

string myRegex;
switch (fileType)
{
    case "pd":
        myRegex = "^PD_";
        break;
    case "fx":
        myRegex = "^FX_";
        break;
    default:
        System.Diagnostics.Debug.WriteLine("File type not valid.");
        myRegex = "*";
        break;
}
fileList = fileList.Where(x => Regex.IsMatch(x.FileName, myRegex));
© www.soinside.com 2019 - 2024. All rights reserved.