2010-06-29 55 views
2

:我的應用程序演練遞歸到驅動器/文件夾的用戶指定(通過的FolderBrowserDialog),去正則表達式模式沒有顯示我有以下代碼匹配

public void DriveRecursion(string retPath) 
    { 
     string pattern = @"[~#&!%\+\{\}]+"; 

     Regex regEx = new Regex(pattern); 

     string[] fileDrive = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories); 
     List<string> filePath = new List<string>(); 
     List<string> filePaths = new List<string>(); 


     dataGridView1.Rows.Clear(); 
     try 
     { 
      foreach (string fileNames in fileDrive) 
      { 
       SanitizeFileNames sw = new SanitizeFileNames(); 


       if (regEx.IsMatch(fileNames)) 
       { 
        string fileNameOnly = Path.GetFileName(fileNames); 
        string pathOnly = Path.GetDirectoryName(fileNames); 

        DataGridViewRow dgr = new DataGridViewRow(); 
        filePath.Add(fileNames); 
        dgr.CreateCells(dataGridView1); 
        dgr.Cells[0].Value = pathOnly; 
        dgr.Cells[1].Value = fileNameOnly; 
        dataGridView1.Rows.Add(dgr); 
        //filePath.Add(fileNames); 
        filePaths.Add(fileNames); 
        paths.Add(fileNames); 
        //sw.FileCleanup(filePaths); 

       } 

       else 
       { 
        continue; 
        //DataGridViewRow dgr2 = new DataGridViewRow(); 
        //dgr2.Cells[0].Value = "No Files To Clean Up"; 
        //dgr2.Cells[1].Value = ""; 
       } 

      } 

     } 
     catch (Exception e) 
     { 
      StreamWriter sw = new StreamWriter(retPath + "ErrorLog.txt"); 
      sw.Write(e); 

     } 

    } 

什麼我tryign做到的是通過我的if語句。如果文件包含我的正則表達式模式中定義的任何字符,它將輸出到我的datagridview。如果不是,則不要在datagridview上顯示它。

由於某種原因,我的代碼似乎會拾取文件夾中的所有文件 - 不僅僅是具有RegEx模式中的字符的文件。我已經看了很長一段時間了,我不確定這是爲什麼會發生。任何人有任何想法,也許我不捕捉?

+0

你有一些示例文件名的名稱? – Iain 2010-06-29 15:55:33

回答

2

「\」將被視爲方括號內的文字而不是轉義字符。這些可能與您的文件路徑匹配。

嘗試:

string pattern = @"[~#&!%+{}]+"; 
1

沒錯,你已經使用轉義字符和指定的字符串被用@符號

基本上從字面上看@「cfnejbncie」是指把整個字符串字面。即你沒有逃脫任何東西,就像整個字符串都逃過了一樣。所以/實際上被用作正則表達式的一部分。

+1

這不就是我說的嗎? :d。我相信有一半時間來描述這個問題是它的一半!我的確的意思是\並沒有逃避正則表達式中的下列字符,它只是一個字符串中的正則表達式。 – Robert 2010-06-29 16:10:39

1

嗯。這對我很好:

var regEx = new Regex(@"[~#&!%\+\{\}]+"); 
var files = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories); 

foreach (var fileName in files.Where(fileName => regEx.IsMatch(fileName))) 
{ 
    Console.WriteLine(fileName); 
} 
+0

是的,但他確實聲明他的代碼可以獲取所有文件,而不僅僅是那些具有特殊字符的文件。 – Robert 2010-06-29 16:08:43

+0

@羅伯特,我知道,但上面的代碼並沒有拿起所有的文件 - 只有那些在他們的特殊字符。 – 2010-06-29 16:13:57

+0

它可能是這條線的B/C,它適合你嗎? foreach(var fileName在files.Where(fileName => regEx.IsMatch(fileName))) 我將如何在我的代碼中實現這個?我不熟悉Where ... – yeahumok 2010-06-29 16:59:23