c - 使用 Posix 正则表达式搜索多个 URL 模式

标签 c regex posix posix-ere

我正在尝试将 URL 字符串与数百个模式进行匹配。我正在使用 regcomp()。我的理解是我可以将所有这 100 个模式组合成一个由 () 分隔的正则表达式,并且可以通过一次调用 regcomp() 进行编译。正确吗?

我尝试过这个,但不知何故它不起作用。在此示例中,我尝试匹配 4 个模式。输入 Url_file 有 4 个输入字符串 www.aaa.com www.bb.cc harom.bb.cc/dhkf dup.com。我期望所有 4 个字符串都匹配,但我的程序返回“不匹配”。

我还需要知道子字符串模式的哪一部分匹配。

int processUrlPosixWay(char *url_file) {
    regex_t compiled_regex;
    size_t max_groups;
    size_t errcode;
    int regflags = REG_EXTENDED|REG_ICASE|REG_NEWLINE;
    char buf[1024];
    const char* arg_regex = "(.*.aaa.com)(www.bb.*)(harom.bb.cc/d.*)(dup.com)";
    //  const char* arg_regex = ".*bb~.cc/d~.*";

    // const char* arg_string = argv[3];

    FILE* fp = fopen(url_file, "r");
    if (fp == NULL)
    {
        pa_log("Error while opening the %s file.\n", url_file);
        return FAILURE;
    }
    // Compile the regex. Return code != 0 means an error.
    if ((errcode = regcomp(&compiled_regex, arg_regex, regflags))) {
        report_regex_error(errcode, &compiled_regex);
        fclose(fp);
        return FAILURE;
    }

    {
        max_groups = compiled_regex.re_nsub;
        printf("max groups %zu",max_groups);
        regmatch_t match_groups[max_groups];

        while (fscanf(fp,"%s",buf) != EOF) {
            if (regexec(&compiled_regex, buf,
                        max_groups, match_groups, 0) == 0) {
                // Go over all matches. A match with rm_so = -1 signals the end
                for (size_t i = 0; i < max_groups; ++i) {
                    if (match_groups[i].rm_so == -1)
                        break;
                    printf("Match group %zu: ", i);
                    for (regoff_t p = match_groups[i].rm_so;
                            p < match_groups[i].rm_eo; ++p) {
                        putchar(arg_regex[p]);
                    }
                    putchar('\n');
                }
                printf(" match\n");

            } else {
                printf("No match\n");
            }
        }
    }
    fclose(fp);
    return 0;
}

最佳答案

正则表达式中的()用于标识一个组;所以你的正则表达式表示应该按指定的顺序包含所有 4 个 URL。

如果您用 | 将它们分开,则表明它们都是替代方案,并且按照您想要的方式运行。

关于c - 使用 Posix 正则表达式搜索多个 URL 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50661320/

相关文章:

Java 正则表达式 : Match any words word and must contain a certain work but except one word

php - 至少包含其中之一的正则表达式

linux - 抑制makefile中命令调用的回声?

c - 获取系统调用ID并将其存储在.txt文件中(LINUX)

C : Passing bi-dimensional array of pointers as argument

java - 使用垂直空白字符作为 java 扫描器分隔符在每个末尾扫描空字符串

c - 如何匹配open和stat mode_t?

c++ - 将 Linux 打开、读取、写入、关闭功能转换为在 Windows 上工作

c - 使用strtok()将从socket接收到的数据分成一个数组

c - 为什么 linux 线程函数在 windows 中工作?