Looking for files with matching templates in a C # directory?

string fileName = ""; string sourcePath = @"C:\vish"; string targetPath = @"C:\SR"; string sourceFile = System.IO.Path.Combine(sourcePath, fileName); string destFile = System.IO.Path.Combine(targetPath, fileName); string pattern = @"23456780"; var matches = Directory.GetFiles(@"c:\vish") .Where(path => Regex.Match(path, pattern).Success); foreach (string file in matches) { Console.WriteLine(file); fileName = System.IO.Path.GetFileName(file); Console.WriteLine(fileName); destFile = System.IO.Path.Combine(targetPath, fileName); System.IO.File.Copy(file, destFile, true); } 

My above program works well with one template.

I use the above program to search for files in a directory with an appropriate template, but in my case I have several templates, so I need to pass several templates in the variable string pattern as an array, but I do not have any idea how I can manipulate this template in Regex.Match.

Can anybody help me?

+6
source share
4 answers

You can add OR to the regular expression :

 string pattern = @"(23456780|otherpatt)"; 
+9
source

change

  .Where(path => Regex.Match(path, pattern).Success); 

to

  .Where(path => patterns.Any(pattern => Regex.Match(path, pattern).Success)); 

where the patterns are IEnumerable<string> , for example:

  string[] patterns = { "123", "456", "789" }; 

If the array has more than 15 expressions, you can increase the cache size:

  Regex.CacheSize = Math.Max(Regex.CacheSize, patterns.Length); 

see http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.cachesize.aspx for more information.

+4
source

Aleroot's answer is the best, but if you want to do this in your code, you can also do it like this:

  string[] patterns = new string[] { "23456780", "anotherpattern"}; var matches = patterns.SelectMany(pat => Directory.GetFiles(@"c:\vish") .Where(path => Regex.Match(path, pat).Success)); 
+2
source

In the simplest form, you can do, for example,

 string pattern = @"(23456780|abc|\.doc$)"; 

this will correspond to files with the selected template or files with the abc template or files with the extension .doc

A link to the templates available for the Regex class can be found here.

+1
source

Source: https://habr.com/ru/post/917415/


All Articles