代码之家  ›  专栏  ›  技术社区  ›  B--rian Optider

如何重用Regex变量?

  •  1
  • B--rian Optider  · 技术社区  · 4 年前

    是否有方法覆盖类型为的变量的值 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));
    

    工具书类

    1 回复  |  直到 4 年前
        1
  •  4
  •   Dmitry Bychenko    4 年前

    我建议 组织 将模式转换为 词典 switch ... case :

     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.");