【问题标题】:c++ regular expression to list all files in a directory except hidden files (start with .)c ++正则表达式列出目录中除隐藏文件以外的所有文件(以.开头)
【发布时间】:2023-01-11 05:13:11
【问题描述】:

我有一个目录内容列表的字符串数组。

我想列出所有不以“.”开头的字符串。

因此,从列表中,正则表达式不应包含".hid.mp3"".Hidden.txt"

有人可以为以下代码建议 fileRegex 吗?

string fileList[] = {"test.png", "Hellozip.zip", "123.mp3", "hid.mp3", "hid.file.png", "sp ace.png", "comm(a.mp3", ".Hidden.txt"};

for(auto& file : fileList)
{
    if (std::regex_match(file, std::regex(fileRegex, std::regex_constants::icase)) == true)
    {
        cout << file << " - Match\n";
    }
    else
    {
        cout << file << " - No Match\n";
    }
}

预期输出应为:

test.png - Match
Hellozip.zip - Match
123\.mp3 - Match
.hid.mp3 - No Match
hid.file.png - Match
sp ace.png - Match
comm(a.mp3 - Match
.Hidden.txt - No Match

我试过这个,但没有用:

"\[\\w-\]*\\.{0,1}\[\\w- ()\]*\\.(png|jpg|zip|mp3|txt)"

编辑:我可以处理“。”,“..”作为特殊情况,因此从问题中删除。

【问题讨论】:

  • 如果没有正则表达式,这是完全微不足道的。有充分的理由让它变得更难吗?
  • 为什么要为此使用正则表达式?检查. 的第一个字符并删除文件不是更容易吗?然后将 ... 添加到列表中(因为每一个目录有那些)?
  • 另一个提示使用std::string::find_first_of('.')
  • 您熟悉“现在您有两个问题”这句话吗?如果没有,请谷歌。
  • @JerryCoffin 在大多数(所有?)类 unix 系统上,根目录有一个 .. 链接回根目录。

标签: c++ regex


【解决方案1】:

怎么样

 ^[^.].*$

似乎工作

【讨论】:

    猜你喜欢
    • 2011-02-23
    • 2011-02-22
    • 2015-08-14
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 2018-01-22
    • 1970-01-01
    相关资源
    最近更新 更多