Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,911 questions

51,843 answers

573 users

How to declare a RegEx with character repetition to match the strings "http", "htttp", "httttp", etc in C

1 Answer

0 votes
#include <stdio.h>
#include <regex.h>

int match_regex(const char *pattern, const char *test_string) {
    regex_t regex;
    int reti;

    // Compile the regex pattern
    reti = regcomp(&regex, pattern, REG_EXTENDED);
    if (reti) {
        printf("Regex compilation failed.\n");
        return 0;
    }

    // Match the test string
    reti = regexec(&regex, test_string, 0, NULL, 0);
    regfree(&regex); // Free memory

    return reti == 0;
}

int main() {
    const char *pattern = "htt+p";

    const char *tests[] = {"http", "htttp", "httttp", "httpp", "htp"};
    int test_count = sizeof(tests) / sizeof(tests[0]);

    for (int i = 0; i < test_count; i++) {
        printf("Test %d matches: %s\n", i + 1, match_regex(pattern, tests[i]) ? "true" : "false");
    }

    return 0;
}

// Matches "httpp": True or false, depending on how matches() method works


/*
run:

Test 1 matches: true
Test 2 matches: true
Test 3 matches: true
Test 4 matches: true
Test 5 matches: false

*/

 



answered May 15, 2025 by avibootz
...