使用正则表达式搜索文件的 Cakephp 文件和文件夹 class

Cakephp Files and Folder class with regex to search for file

我正在创建某种 shell 用于删除备份文件。我曾经使用关键字 'bkp' 创建原始文件的备份。它可以是文件名中的任意位置,例如 ["abc.bkp.ctp"、"abc-bkp.ctp"、abc_bkp.ctp"、"bkp_abc.ctp"]。我的意思是任何方式。我希望使用 shell 删除所有文件。我正在使用 Cakephp 的文件 N 文件夹 Class“http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html”。我将如何编写正则表达式来搜索这些文件。

我的 shell 逻辑是什么。

    public function removeBkp() {
        $path = BASE_PATH . DS . APP_DIR . DS;
        $count = 0;

        $this->out("", 2);
        $this->out("-------------------------------------", 1);
        $this->out("Path : " . $path, 1);
        $this->out("FILES DETAILS", 1);
        $this->out("-------------------------------------", 2);
        $dir = new Folder($path);
        // Need to seach bkp files here 
        $defaultFiles = $dir->findRecursive("(bkp)");

        $results = $defaultFiles;
        if ($results == null || empty($results)) {
            $this->out("No file to delete.", 3);
        } else {
            foreach ($results as $file) {
                // unlink($file);
                $this->out("File removed - " . $file, 1);
                $count++;
            }
            $this->out("Total files: " . count($results), 1);
        }
    }

您可以使用此正则表达式匹配所有文件名:

([\w._-]*bkp[\S]*?\.ctp)

假设只有 ._- 用于拆分文件,您可能需要向该字符添加更多内容 class。

此正则表达式还假定文件始终以 ctp 结尾。

演示:https://regex101.com/r/tB9nM9/1

编辑:如果您希望匹配任何扩展名,您可以使用 \w{3} 概括扩展名。其中 3 是长度,如果需要,您可以在此处添加方差,但通常越具体越好。

([\w._-]*bkp[\S]*\.\w{3})

演示:https://regex101.com/r/tB9nM9/2