簡體   English   中英

如何重用正則表達式變量?

[英]How to re-use a Regex variable?

有沒有辦法覆蓋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));

但是,這會導致各種類型轉換錯誤。 任何建議如何解決這個問題?

參考

我建議將模式組織字典並擺脫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.");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM