首页 > 解决方案 > 使用 Posix 正则表达式搜索多个 URL 模式

问题描述

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

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

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

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;
}

标签: cregexposixposix-ere

解决方案


()则表达式中的 用于标识组;所以你的正则表达式是说应该有所有 4 个这些 URL 以指定的顺序。

如果你用|'s 将它们分开,这将表明它们都是一个替代品,并且按照你想要的方式行事。


推荐阅读