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

时间:2018-06-02 21:28:56

标签: c regex posix posix-ere

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

我尝试了这个,但不知怎的,它不起作用。在这个例子中,我试图匹配4种模式。输入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;
}

1 个答案:

答案 0 :(得分:0)

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

如果您将它们与|分开,则表明它们都是替代品,并且表现得像您想要的那样。

相关问题