How to check if a string contains only letters and numbers using RegEx in C

1 Answer

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

bool isAlphanumeric(const char* str) {
    // Define the regular expression for alphanumeric characters
    const char* alphanumericRegex = "^[a-zA-Z0-9]+$";
    regex_t regex;
    int result;

    // Compile the regular expression
    if (regcomp(&regex, alphanumericRegex, REG_EXTENDED) != 0) {
        printf("Could not compile regex.\n");
        return false;
    }

    // Execute the regular expression
    result = regexec(&regex, str, 0, NULL, 0);
    regfree(&regex); // Free memory allocated to the regex structure

    // If result is 0, the string matches the regex
    return result == 0;
}

int main() {
    const char* str = "VuZ3q7J4wo35Pi";

    if (isAlphanumeric(str)) {
        printf("The string contains only letters and numbers.\n");
    } else {
        printf("The string contains characters other than letters and numbers.\n");
    }

    return 0;
}


/*
run:

The string contains only letters and numbers.

*/

 



answered Mar 25, 2025 by avibootz
...