我有以下代码:
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);
}
}
我试图完成的是我的应用程序递归地钻取用户指定的驱动器/文件夹(通过 FolderBrowserDialog)并通过我的 if 语句。如果文件包含我的正则表达式模式中定义的任何字符,它将输出到我的数据 GridView 。如果没有,则不要在数据 GridView 上显示它。
现在出于某种原因,我的代码似乎提取了一个文件夹中的所有文件——而不仅仅是那些在我的 RegEx 模式中带有字符的文件。我已经研究了很长时间了,但不确定为什么会这样。有人有我没听懂的想法吗?
最佳答案
“\”将被视为方括号内的文字而不是转义字符。这些可能与您的文件路径匹配。
尝试:
string pattern = @"[~#&!%+{}]+";
关于c# - 正则表达式模式不显示匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3142396/