2010-06-29 57 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