【问题标题】:Searching multiple URL pattern with Posix regex使用 Posix 正则表达式搜索多个 URL 模式
【发布时间】:2018-06-02 21:28:55
【问题描述】:

我正在尝试匹配具有 100 种模式的 URL 字符串。我正在使用 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;
}

【问题讨论】:

  • “感谢对此的快速而详细的回应” 你太粗鲁了。您在这里寻求免费的编程帮助。
  • 为什么这个问题有 Perl 标签?
  • stackoverflow 建议
  • 请记住,正则表达式并不是本质上锚定的。 .*.aaa.com 与 .aaa.com 匹配的字符串完全相同,其他字符串也是如此。

标签: c regex posix posix-ere


【解决方案1】:

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

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

【讨论】:

  • 有没有办法让我知道在 regexec 中匹配了哪个替代方案?我知道 regmatch_t pmatch 可以判断它匹配哪个组,但我不知道如果用“|”分隔,如何知道哪个模式匹配?感谢您花时间回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多