c - C中目录和文件列表的正则表达式

标签 c regex linux

我正在尝试编写一个表达式,在列出目录内容时过滤掉几种类型的目录和文件。也就是说,我想避免列出当前目录 (.)、上层目录 (..)、隐藏文件和其他更具体的目录。

这是我现在拥有的:

[\\.+]|cgi-bin|recycle_bin

但是,它不匹配...、recycle_bin 或cgi-bin。如果我删除所有 | 操作数并将表达式仅保留为 [\\.+],它会起作用(匹配 . .. 等)。这很奇怪,因为我很确定 | = OR。我错过了什么吗?

更新 1:这是我使用的代码:

            regex_t regex;
            int reti;
            char msgbuf[100];

            /* Compile regular expression */
            reti = regcomp(&regex, "[\\.+]|cgi-bin|recycle_bin", 0);


            if( reti )
            { 
                fprintf(stderr, "Could not compile regex\n");
                exit(1);
            }

            reti = regexec(&regex, entry->d_name, 0, NULL, 0);
            if( !reti ){

                printf("directoy %s found -> %s", path, entry->d_name);
                printf("\n");

            }
            else if( reti == REG_NOMATCH ){

                //if the directory is not filtered out, we add it to the watch list
                printf("good dir %s", entry->d_name);                    
                printf("\n");

            }
            else{
                regerror(reti, &regex, msgbuf, sizeof(msgbuf));
                fprintf(stderr, "Regex match failed: %s\n", msgbuf);
            }

最佳答案

使用"extended REs" .用regular ("obsolete") ones , | 是一个普通字符。

regcomp(..., REG_EXTENDED);

另见 regcomp() description .

关于c - C中目录和文件列表的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10464646/

相关文章:

编译具有有限库访问权限的程序

linux - 从 Vagrant 脚本设置 RHEL box 的 ip

c - 从函数传递结构数组

c - C 中的指针和数组

c - 递归释放二叉树时出现段错误

用于检查时间格式的 JavaScript 正则表达式

c - 在 fprintf 中格式化输出

mysql - 使用 REGEXP 进行 SQL 选择返回错误的数据行

java - 如何在 Java 中格式化非纯日期?

c# - SmtpClient.Send 不适用于 linux 环境