The Regular Expression Library

From the preceding discussion, you can appreciate that implementing regular expression searches on your own is less than trivial. However, regular expressions can be part of your programs with the help of the C library.

Compiling Regular Expressions

For efficiency, a regular expression is first compiled into an opaque data type regex_t. The function synopsis for compiling a regular expression is as follows:

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

int regcomp(regex_t *preg, const char *pattern, int cflags);

typedef struct {
    int         re_magic;
    size_t      re_nsub;   /* number of parenthesized subexpressions */
    const char  *re_endp;  /* end pointer for REG_PEND */
    struct re_guts *re_g;  /* opaque */
}  regex_t;

pattern is the ...

Get Advanced UNIX Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.