简体   繁体   中英

Regex containing a specific word

I need load files from directory same this example: "Client_Test_delete.xlsx". But loading all files with _delete.xlsx extension. How create valid testMask?

var testMask = @"^[Client]+(.*_delete.xlsx*).*$";
var searchPattern = new Regex(testMask, RegexOptions.IgnoreCase);
var files = Directory.GetFiles(fullPath).Where(f => searchPattern.IsMatch(f));

Files in directory:

c:\Client_Test_delete.xlsx"
c:\Some_Test_delete.xlsx"

The System.IO.Directory.GetFiles has an overload that have a search pattern, try this. It's more simple. [i don't know the regular expressions]

http://msdn.microsoft.com/it-it/library/ms143316%28v=vs.110%29.aspx

  string txt="Client_Test_delete.xlsx";

  string re1="(Client)";    // Word 1
  string re2=".*?"; // Non-greedy match on filler
  string re3="_";   // Uninteresting: c
  string re4=".*?"; // Non-greedy match on filler
  string re5="(_)"; // Any Single Character 1
  string re6="(delete)";    // Word 2
  string re7="(\\.)";   // Any Single Character 2
  string re8="(xlsx)";  // Variable Name 1

  Regex r = new Regex(re1+re2+re3+re4+re5+re6+re7+re8,RegexOptions.IgnoreCase|RegexOptions.Singleline);
  Match m = r.Match(txt);
  if (m.Success)
  {
     //Delete file
  }

try with this regex:

^(?:[\\w]\\:)+\\*(Client).*?_.*?_delete.xlsx

I update the expression with Client part.

It Match: "c:\\Client_Test_delete.xlsx"
and fail with "c:\\Some_Test_delete.xlsx"

You can try like this:

var testMask = @"^Client_[a-z\d]+_delete.xlsx?$";   // OR "^Client_[^_]+_delete.xlsx?$"
var searchPattern = new Regex(testMask, RegexOptions.IgnoreCase);
var files = Directory.GetFiles(fullPath).Where(f => searchPattern.IsMatch(f));

This will match files with .xlsx or .xls extensions, and first word client and last word delete .

Hope it will give you an idea to go ahead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM