Regular Expressions (C)

Regular Expressions in C use POSIX syntax and are a little weird.

How It Works

Compile Pattern

To compile the regex pattern, use int regcomp(regex_t *preg, const char *regex, int cflags).

Match It To String

To match, use int regexec(const regex_t *preg, const char *string, size_t nmatch, regmatch_t pmatch[], int eflags).

Catch Any Errors

Use size_t regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)[4].

Free Up Memory When Finished

Use void regfree(regex_t *preg).

Example

Check out the thorough example from Ben Bullock[1] using the link below, or if the page doesn't work, you can find it locally here. A more basic example can be found below, from Per-Olof Pettersson[5]:

#include <sys/types.h>
#include <regex.h>
#include <stdio.h>

int main (int argc, char *argv[]) {
  regex_t regex;
  int reti;
  char msgbuf[100];

  /* Compile regular expression */
  reti = regcomp(&regex, "^a[[:alnum:]]", 0);
  if (reti) {
    fprintf(stderr, "Could not compile regex\n");
    exit(1); 
  }

  /* Execute regular expression */
  reti = regexec(&regex, "abc", 0, NULL, 0);
  if (!reti) {
    puts("Match");
  } else if (reti == REG_NOMATCH) {
    puts("No match");
  } else {
    regerror(reti, &regex, msgbuf, sizeof(msgbuf));
    fprintf(stderr, "Regex match failed: %s\n", msgbuf);
    exit(1);
  }

  /* Free compiled regular expression if you want to use the regex_t again */
  regfree(&regex);

  return 0;
}

References

  1. https://www.lemoda.net/c/unix-regex/
  2. http://www.gnu.org/savannah-checkouts/gnu/libc/manual/html_node/Regular-Expressions.html
  3. http://www.gnu.org/savannah-checkouts/gnu/libc/manual/html_node/Flags-for-POSIX-Regexps.html
  4. https://linux.die.net/man/3/regexec
  5. http://web.archive.org/web/20160308115653/http://peope.net/old/regex.html

Last modified: 202401040446