在目录c#中查找具有匹配模式的文件?
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); }
我的上述程序适用于单一模式。
我正在使用上面的程序来查找具有匹配模式的目录中的文件但在我的情况下我有多个模式所以我需要将string pattern
变量中的多个模式作为数组传递但我不知道我是怎么回事可以在Regex.Match中操纵这些模式。
谁能帮我?
你可以在正则表达式中加一个OR :
string pattern = @"(23456780|otherpatt)";
更改
.Where(path => Regex.Match(path, pattern).Success);
至
.Where(path => patterns.Any(pattern => Regex.Match(path, pattern).Success));
其中patterns是IEnumerable
,例如:
string[] patterns = { "123", "456", "789" };
如果arrays中有超过15个表达式,则可能需要增加缓存大小:
Regex.CacheSize = Math.Max(Regex.CacheSize, patterns.Length);
有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.cachesize.aspx 。
Aleroot的答案是最好的,但是如果你想在你的代码中做到这一点,你也可以这样做:
string[] patterns = new string[] { "23456780", "anotherpattern"}; var matches = patterns.SelectMany(pat => Directory.GetFiles(@"c:\vish") .Where(path => Regex.Match(path, pat).Success));
例如,您可以使用最简单的forms
string pattern = @"(23456780|abc|\.doc$)";
这将匹配您选择的模式或具有abc模式的文件或扩展名为.doc的文件
可在此处找到可用于Regex类的模式的参考