[Previous]
[Contents]
[Next]

regcomp()

compile a regular expression, for use with regexec()

Synopsis:

#include <regex.h>
int regcomp( regex_t *preg,
             const char *pattern,
             int cflags );

Description:

The regcomp() function prepares the regular expression, preg, for use by the function regexec(), from the specification pattern and cflags. The member re_nsub of preg is set to the number of subexpressions in pattern. The argument cflags is the bitwise inclusive OR of zero or more of the following flags:

REG_EXTENDED
Use Extended Regular Expressions.
REG_NEWLINE
Treat <newline> as a regular character.
REG_ICASE
Ignore differences in case.
REG_NOSUB
Report only success/failure in regexec().

The functions that deal with regular expressions (regcomp(), regerror(), regexec(), and regfree()) support two classes of regular expressions, the Basic and Extended Regular Expressions. These classes are rigorously defined in IEEE P1003.2, Regular Expression Notation.

Basic Regular Expressions

The Basic Regular Expressions are composed of these terms:

x$
x at end of line ($ must be the last term)
^x
x at beginning of line (^ must be first term)
x*
zero or more occurrences of x
.
any single character (except newline)
c
the character c
xc
x followed by the character c
cx
character c followed by x
[cd]
the characters c or d
[c-d]
all characters between c and d, inclusive
[^c]
any character but c
[[:classname:]]
any of the following classes:
[[=c=]]
all character in equivalence class with c
[[=.=]]
all collating elements
x{m,n}
m through n occurrences of x
\c
character c even if c is an operator
\(x\)
a labeled subexpression x
\m
the mth subexpression encountered
xy
expression x followed by y

Extended Regular Expressions

The Extended Regular Expressions also include:

x+
one or more occurrences of x
x?
zero or one occurrences of x
(x)
subexpression x (for precedence handling)
x|y
expression x OR y

Returns:

Zero if successful, nonzero if the function fails for any reason.

Examples:

/*
    The following example prints out all lines
    from FILE "f" that match "pattern".
*/
#include <stdio.h>
#include <regex.h>

void grep( char *pattern, FILE *f )
  {
    int t;
    regex_t re;
    char    buffer[MAX_INPUT];

    if ((t=regcomp( &re, pattern, REG_NOSUB )) != 0) {
      regerror(t, &re, buffer, sizeof buffer);
      fprintf(stderr,"grep: %s (%s)\n",buffer,pattern);
      return;
    }
    while( fgets( buffer, MAX_INPUT, f ) != NULL ) {
      if( regexec( &re, buffer, 0, NULL, 0 ) == 0 ) {
        fputs( buffer, stdout );
      }
    }
    regfree( &re );
  }

Classification:

POSIX 1003.2

Safety:
Interrupt handler No
Signal handler No
Thread No

See also:

regerror(), regexec(), regfree()


[Previous]
[Contents]
[Next]