如何重用正则表达式变量?

时间:2020-02-11 10:22:58

标签: c# regex switch-statement

是否有一种方法可以覆盖类型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_"); // probability of default
    fileList = fileList.Where(x => myRegexPD.IsMatch(x.FileName));
    break;
  case "fx":  // exchange rate
    Regex myRegexFx = new Regex("^FX_"); // exchange rate
    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));

但是,这会导致各种类型转换错误。有什么建议解决这个问题吗?

参考文献

1 个答案:

答案 0 :(得分:4)

我建议将模式组织 dictionary 中,并摆脱switch ... case

 //TODO: I've hardcoded the patterns, but you may well want to generate them:
 // s_Patterns = MyFileTypes.ToDictionary(t => t.Name, $"^{t.Name.ToUpper()}_"); 
 private static Dictionary<string, string> s_Patterns = new Dictionary<string, string>() {
   {"pd", "^PD_"},
   {"fx", "^FX_"},
 };

然后您可以轻松使用它们:

 if (s_Patterns.TryGetValue(fileType, out var pattern))
   fileList = fileList.Where(x => Regex.IsMatch(x.FileName, pattern));
 else
   System.Diagnostics.Debug.WriteLine("File type not valid.");