PREV UP NEXT Regex

7.2.3: POSIX Matching

Matching the posix way means trying to match a null-terminated string starting at its first character. Once you've compiled a pattern into a pattern buffer (see POSIX Regular Expression Compiling), you can ask the matcher to match that pattern against a string using:

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

preg is the address of a pattern buffer for a compiled pattern. string is the string you want to match.

See Using Byte Offsets, for an explanation of pmatch. If you pass zero for nmatch or you compiled preg with the compilation flag REG_NOSUB set, then regexec will ignore pmatch; otherwise, you must allocate it to have at least nmatch elements. regexec will record nmatch byte offsets in pmatch, and set to -1 any unused elements up to pmatch[nmatch] - 1.

eflags specifies execution flags---namely, the two bits REG_NOTBOL and REG_NOTEOL (defined in regex.h). If you set REG_NOTBOL, then the match-beginning-of-line operator (see Match-beginning-of-line Operator) always fails to match. This lets you match against pieces of a line, as you would need to if, say, searching for repeated instances of a given pattern in a line; it would work correctly for patterns both with and without match-beginning-of-line operators. REG_NOTEOL works analogously for the match-end-of-line operator (see Match-end-of-line Operator); it exists for symmetry.

regexec tries to find a match for preg in string according to the syntax in preg's syntax field. (See POSIX Regular Expression Compiling, for how to set it.) The function returns zero if the compiled pattern matches string and REG_NOMATCH (defined in regex.h) if it doesn't.