c# - 正则表达式模式不显示匹配项

标签 c# regex

我有以下代码:

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/

相关文章:

c# - Entity Framework 5 : Why is my entity's collection property empty?

c# - 如何清除 C# 中的事件订阅?

javascript 正则表达式 unicode 帮助

regex - sed 命令适用于命令行,但不适用于 bash 脚本

java - 如何优化基于正则表达式的大日志文件解析?

sql-server - 什么是 SQL Server 中的 regexp_replace 等价物

c# 从静态函数中打印类名

c# - 除了测试,依赖注入(inject)有什么比静态类/方法更好的地方?

c# - Gitversion 回滚了 AzureDevops 构建管道中我的 NuGet 包的版本号

正则表达式