8
 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のこれらのパターン。

誰か助けてもらえますか?

4

4 に答える 4

9

正規表現にORを入れることができます:

string pattern = @"(23456780|otherpatt)";
于 2012-06-05T07:35:11.120 に答える
4

変化する

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

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

ここで、patternsは、IEnumerable<string>たとえば次のようになります。

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

配列に15を超える式がある場合は、キャッシュサイズを増やすことをお勧めします。

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

詳細については、 http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.cachesize.aspxを参照してください。

于 2012-06-05T07:37:07.893 に答える
2

Alerootの答えが最善ですが、コードでそれを実行したい場合は、次のようにすることもできます。

   string[] patterns = new string[] { "23456780", "anotherpattern"};
        var matches = patterns.SelectMany(pat => Directory.GetFiles(@"c:\vish")
            .Where(path => Regex.Match(path, pat).Success));
于 2012-06-05T07:41:53.520 に答える
1

最も単純な形式では、たとえば

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

これは、選択したパターンのファイル、abcパターンのファイル、または拡張子が.docのファイルと一致します。

正規表現クラスで使用可能なパターンのリファレンスは、ここにあります。

于 2012-06-05T07:36:09.050 に答える