-1

I am trying to match a URL string with 100s of patterns against. I am using regcomp(). My understanding is I can club all these 100s of pattern into a single regex separated by () and can compile with single call of regcomp(). Is it correct?

I tried this but somehow it is not working. In this example, I am trying to match with 4 patterns. input Url_file has 4 input strings www.aaa.com www.bb.cc harom.bb.cc/dhkf dup.com. I was expecting a match for all 4 strings but my program is returning No match.

Also I need to know which part of substring patter 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;
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Andy Garg
  • 31
  • 2

1 Answers1

0

The () in a regex are used to identify a group; so your regex is saying there should be all 4 of these URLs in the specified order.

If you separate them with |'s, that will indicate that they are each an alternative, and behave the way it seems that you want.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • is there a way i can know which alternative got matched in regexec? I know regmatch_t pmatch can tell which group it matched but I have no idea how to know which pattern got matched if separated by '|' ? Thanks for taking time to answer. – Andy Garg Jun 03 '18 at 01:36