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 a single pattern.
I'm using above program to find the files in a directory with a matching pattern but in my case I've multiple patterns so i need to pass multiple pattern in string pattern
variable as an array but I don't have any idea how i can manipulate those pattern in Regex.Match.
Can anyone help me?
You can put an OR in the regex :
string pattern = @"(23456780|otherpatt)";
change
.Where(path => Regex.Match(path, pattern).Success);
to
.Where(path => patterns.Any(pattern => Regex.Match(path, pattern).Success));
where patterns is an IEnumerable<string>
, for example:
string[] patterns = { "123", "456", "789" };
If you have more then 15 expressions in the array, you may want to 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.
Aleroot's answer is the best, but if you wanted to do it in your code, you could 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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With