簡體   English   中英

RegEx模式未顯示匹配項

[英]RegEx pattern not showing matches

我有以下代碼:

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語句。 如果文件包含我的正則表達式模式中定義的任何字符,它將輸出到我的datagridview。 如果不是,則不要在datagridview上顯示它。

出於某種原因,我的代碼現在似乎拾取了文件夾中的所有文件,而不僅僅是RegEx模式中帶有字符的文件。 我已經看了很長時間了,我不確定為什么會這樣。 有人有任何想法也許我沒有抓住嗎?

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

嘗試:

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

是的,您已經使用了轉義字符並指定了使用@符號從字面上讀取字符串

基本上@“ cfnejbncie”表示按字面意義取整個字符串。 也就是說,您什么也沒逃脫,就像整個字符串都逃脫了一樣。 因此,/實際上已被用作正則表達式的一部分。

嗯。 這對我來說很好:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM