#include #include #include // Receives a regular expression by command line argument // Test texts given in standard input against the regular expression // http://pubs.opengroup.org/onlinepubs/009695399/functions/regcomp.html // Compile with: gcc -Wall -Wextra -std=c11 -o test_regex test_regex.c // Adapted from: https://stackoverflow.com/questions/1085083/regular-expressions-in-c-examples #define SZ_LINE 1024 int main(int argc, char* argv[]) { // One argument is mandatory: the regular expression if ( argc <= 1 ) return fprintf(stderr, "usage: test_regex 'regular expression' [extended|icase|nosub|newline]\n"), 1; // set flags in arguments int cflags = 0; for ( int index = 2; index < argc; ++index ) { if ( strcmp(argv[index], "extended") == 0 ) cflags |= REG_EXTENDED; else if ( strcmp(argv[index], "icase") == 0 ) cflags |= REG_ICASE; else if ( strcmp(argv[index], "NOSUB") == 0 ) cflags |= REG_NOSUB; else if ( strcmp(argv[index], "newline") == 0 ) cflags |= REG_NEWLINE; else fprintf(stderr, "warning: ignoring flag: %s\n", argv[index]); } // Compile the regular expression regex_t regex; int error = regcomp(®ex, argv[1], cflags); if ( error ) return fprintf(stderr, "error: could not compile regex '%s'\n", argv[1]), 1; // While there are lines in stdin char line[SZ_LINE]; while ( fgets(line, SZ_LINE, stdin) ) { // Execute regular expression against line error = regexec(®ex, line, 0, NULL, 0); if ( error == 0 ) puts("Match"); else if (error == REG_NOMATCH) puts("No match"); else { char msgbuf[100]; regerror(error, ®ex, msgbuf, sizeof(msgbuf)); fprintf(stderr, "Regex match failed: %s\n", msgbuf); break; } } // Free memory allocated to the pattern buffer by regcomp() regfree(®ex); return 0; }