Overview
********

A regular expression (or regexp, or pattern) is a text string that describes some (mathematical) set of strings.  A regexp R matches a string S if S is in the set of strings described by R.

Using the Regex library, you can:

  * see if a string matches a specified pattern as a whole, and

  * search within a string for a substring matching a specified pattern.

Some regular expressions match only one string, i.e., the set they describe has only one member.  For example, the regular expression foo matches the string foo and no others.  Other regular expressions match more than one string, i.e., the set they describe has more than one member.  For example, the regular expression f* matches the set of strings made up of any number (including zero) of fs.  As you can see, some characters in regular expressions match themselves (such as f) and some don't (such as *); the ones that don't match themselves instead let you specify patterns that describe many different strings.

To either match or search for a regular expression with the Regex library functions, you must first compile it with a Regex pattern compiling function.  A compiled pattern is a regular expression converted to the internal format used by the library functions.  Once you've compiled a pattern, you can use it for matching or searching any number of times.

The Regex library is used by including regex.h. Regex provides three groups of functions with which you can operate on regular expressions.  One group---the GNU group---is more powerful but not completely compatible with the other two, namely the POSIX and Berkeley UNIX groups; its interface was designed specifically for GNU.

We wrote this chapter with programmers in mind, not users of programs---such as Emacs---that use Regex.  We describe the Regex library in its entirety, not how to write regular expressions that a particular program understands.

Regular Expression Syntax
*************************

Characters are things you can type.  Operators are things in a regular expression that match one or more characters.  You compose regular expressions from operators, which in turn you specify using one or more characters.

Most characters represent what we call the match-self operator, i.e., they match themselves; we call these characters ordinary.  Other characters represent either all or parts of fancier operators; e.g., . represents what we call the match-any-character operator (which, no surprise, matches (almost) any character); we call these characters special.  Two different things determine what characters represent what operators:

 1. the regular expression syntax your program has told the Regex library to recognize, and

 2. the context of the character in the regular expression.

In the following sections, we describe these things in more detail.

Syntax Bits
===========

In any particular syntax for regular expressions, some characters are always special, others are sometimes special, and others are never special.  The particular syntax that Regex recognizes for a given regular expression depends on the current syntax (as set by re_set_syntax) when the pattern buffer of that regular expression was compiled.

You get a pattern buffer by compiling a regular expression.  See GNU Pattern Buffers, for more information on pattern buffers.  See GNU Regular Expression Compiling, and BSD Regular Expression Compiling, for more information on compiling.

Regex considers the current syntax to be a collection of bits; we refer to these bits as syntax bits.  In most cases, they affect what characters represent what operators.  We describe the meanings of the operators to which we refer in Common Operators, GNU Operators, and GNU Emacs Operators.

For reference, here is the complete list of syntax bits, in alphabetical order:

RE_BACKSLASH_ESCAPE_IN_LISTS
     If this bit is set, then \ inside a list (see List Operators quotes (makes ordinary, if it's special) the following character; if this bit isn't set, then \ is an ordinary character inside lists. (see The Backslash Character, for what \ does outside of lists.)

RE_BK_PLUS_QM
     If this bit is set, then \+ represents the match-one-or-more operator and \? represents the match-zero-or-more operator; if this bit isn't set, then + represents the match-one-or-more operator and ? represents the match-zero-or-one operator.  This bit is irrelevant if RE_LIMITED_OPS is set.

RE_CHAR_CLASSES
     If this bit is set, then you can use character classes in lists; if this bit isn't set, then you can't.

RE_CONTEXT_INDEP_ANCHORS
     If this bit is set, then ^ and $ are special anywhere outside a list; if this bit isn't set, then these characters are special only in certain contexts.  See Match-beginning-of-line Operator, and Match-end-of-line Operator.

RE_CONTEXT_INDEP_OPS
     If this bit is set, then certain characters are special anywhere outside a list; if this bit isn't set, then those characters are special only in some contexts and are ordinary elsewhere.  Specifically, if this bit isn't set then *, and (if the syntax bit RE_LIMITED_OPS isn't set) + and ? (or \+ and \?, depending on the syntax bit RE_BK_PLUS_QM) represent repetition operators only if they're not first in a regular expression or just after an open-group or alternation operator.  The same holds for { (or \{, depending on the syntax bit RE_NO_BK_BRACES) if it is the beginning of a valid interval and the syntax bit RE_INTERVALS is set.

RE_CONTEXT_INVALID_DUP
     If this bit is set, then an open-interval operator cannot occur at the start of a regular expression, or immediately after an alternation, open-group or close-interval operator.

RE_CONTEXT_INVALID_OPS
     If this bit is set, then repetition and alternation operators can't be in certain positions within a regular expression.  Specifically, the regular expression is invalid if it has:

       * a repetition operator first in the regular expression or just after a match-beginning-of-line, open-group, or alternation operator; or

       * an alternation operator first or last in the regular expression, just before a match-end-of-line operator, or just after an alternation or open-group operator.

     If this bit isn't set, then you can put the characters representing the repetition and alternation characters anywhere in a regular expression. Whether or not they will in fact be operators in certain positions depends on other syntax bits.

RE_DEBUG
     If this bit is set, and the regex library was compiled with -DDEBUG, then internal debugging is turned on; if unset, then it is turned off.

RE_DOT_NEWLINE
     If this bit is set, then the match-any-character operator matches a newline; if this bit isn't set, then it doesn't.

RE_DOT_NOT_NULL
     If this bit is set, then the match-any-character operator doesn't match a null character; if this bit isn't set, then it does.

RE_HAT_LISTS_NOT_NEWLINE
     If this bit is set, nonmatching lists [^...] do not match newline; if not set, they do.

RE_ICASE
     If this bit is set, then ignore case when matching; otherwise, case is significant.

RE_INTERVALS
     If this bit is set, then Regex recognizes interval operators; if this bit isn't set, then it doesn't.

RE_INVALID_INTERVAL_ORD
     If this bit is set, a syntactically invalid interval is treated as a string of ordinary characters.  For example, the extended regular expression a{1 is treated as a\{1.

RE_LIMITED_OPS
     If this bit is set, then Regex doesn't recognize the match-one-or-more, match-zero-or-one or alternation operators; if this bit isn't set, then it does.

RE_NEWLINE_ALT
     If this bit is set, then newline represents the alternation operator; if this bit isn't set, then newline is ordinary.

RE_NO_BK_BRACES
     If this bit is set, then { represents the open-interval operator and } represents the close-interval operator; if this bit isn't set, then \{ represents the open-interval operator and \} represents the close-interval operator.  This bit is relevant only if RE_INTERVALS is set.

RE_NO_BK_PARENS
     If this bit is set, then ( represents the open-group operator and ) represents the close-group operator; if this bit isn't set, then \( represents the open-group operator and \) represents the close-group operator.

RE_NO_BK_REFS
     If this bit is set, then Regex doesn't recognize \DIGIT as the back reference operator; if this bit isn't set, then it does.

RE_NO_BK_VBAR
     If this bit is set, then | represents the alternation operator; if this bit isn't set, then \| represents the alternation operator.  This bit is irrelevant if RE_LIMITED_OPS is set.

RE_NO_EMPTY_RANGES
     If this bit is set, then a regular expression with a range whose ending point collates lower than its starting point is invalid; if this bit isn't set, then Regex considers such a range to be empty.

RE_NO_GNU_OPS
     If this bit is set, GNU regex operators are not recognized; otherwise, they are.

RE_NO_POSIX_BACKTRACKING
     If this bit is set, succeed as soon as we match the whole pattern, without further backtracking.  This means that a match may not be the leftmost longest; see What Gets Matched? for what this means.

RE_NO_SUB
     If this bit is set, then no_sub will be set to one during re_compile_pattern.  This causes matching and searching routines not to record substring match information.

RE_UNMATCHED_RIGHT_PAREN_ORD
     If this bit is set and the regular expression has no matching open-group operator, then Regex considers what would otherwise be a close-group operator (based on how RE_NO_BK_PARENS is set) to match ).

Predefined Syntaxes
===================

If you're programming with Regex, you can set a pattern buffer's (see GNU Pattern Buffers) syntax either to an arbitrary combination of syntax bits (see Syntax Bits) or else to the configurations defined by Regex. These configurations define the syntaxes used by certain programs---GNU Emacs, POSIX Awk, traditional Awk, Grep, Egrep---in addition to syntaxes for POSIX basic and extended regular expressions.

The predefined syntaxes---taken directly from regex.h---are:

     #define RE_SYNTAX_EMACS 0

     #define RE_SYNTAX_AWK                                                   \
       (RE_BACKSLASH_ESCAPE_IN_LISTS | RE_DOT_NOT_NULL                       \
        | RE_NO_BK_PARENS            | RE_NO_BK_REFS                         \
        | RE_NO_BK_VBAR               | RE_NO_EMPTY_RANGES                   \
        | RE_UNMATCHED_RIGHT_PAREN_ORD)

     #define RE_SYNTAX_POSIX_AWK                                             \
       (RE_SYNTAX_POSIX_EXTENDED | RE_BACKSLASH_ESCAPE_IN_LISTS)

     #define RE_SYNTAX_GREP                                                  \
       (RE_BK_PLUS_QM              | RE_CHAR_CLASSES                         \
        | RE_HAT_LISTS_NOT_NEWLINE | RE_INTERVALS                            \
        | RE_NEWLINE_ALT)

     #define RE_SYNTAX_EGREP                                                 \
       (RE_CHAR_CLASSES        | RE_CONTEXT_INDEP_ANCHORS                    \
        | RE_CONTEXT_INDEP_OPS | RE_HAT_LISTS_NOT_NEWLINE                    \
        | RE_NEWLINE_ALT       | RE_NO_BK_PARENS                             \
        | RE_NO_BK_VBAR)

     #define RE_SYNTAX_POSIX_EGREP                                           \
       (RE_SYNTAX_EGREP | RE_INTERVALS | RE_NO_BK_BRACES)

     /* P1003.2/D11.2, section 4.20.7.1, lines 5078ff.  */
     #define RE_SYNTAX_ED RE_SYNTAX_POSIX_BASIC

     #define RE_SYNTAX_SED RE_SYNTAX_POSIX_BASIC

     /* Syntax bits common to both basic and extended POSIX regex syntax.  */
     #define _RE_SYNTAX_POSIX_COMMON                                         \
       (RE_CHAR_CLASSES | RE_DOT_NEWLINE      | RE_DOT_NOT_NULL              \
        | RE_INTERVALS  | RE_NO_EMPTY_RANGES)

     #define RE_SYNTAX_POSIX_BASIC                                           \
       (_RE_SYNTAX_POSIX_COMMON | RE_BK_PLUS_QM)

     /* Differs from ..._POSIX_BASIC only in that RE_BK_PLUS_QM becomes
        RE_LIMITED_OPS, i.e., \? \+ \| are not recognized.  Actually, this
        isn't minimal, since other operators, such as \`, aren't disabled.  */
     #define RE_SYNTAX_POSIX_MINIMAL_BASIC                                   \
       (_RE_SYNTAX_POSIX_COMMON | RE_LIMITED_OPS)

     #define RE_SYNTAX_POSIX_EXTENDED                                        \
       (_RE_SYNTAX_POSIX_COMMON | RE_CONTEXT_INDEP_ANCHORS                   \
        | RE_CONTEXT_INDEP_OPS  | RE_NO_BK_BRACES                            \
        | RE_NO_BK_PARENS       | RE_NO_BK_VBAR                              \
        | RE_UNMATCHED_RIGHT_PAREN_ORD)

     /* Differs from ..._POSIX_EXTENDED in that RE_CONTEXT_INVALID_OPS
        replaces RE_CONTEXT_INDEP_OPS and RE_NO_BK_REFS is added.  */
     #define RE_SYNTAX_POSIX_MINIMAL_EXTENDED                                \
       (_RE_SYNTAX_POSIX_COMMON  | RE_CONTEXT_INDEP_ANCHORS                  \
        | RE_CONTEXT_INVALID_OPS | RE_NO_BK_BRACES                           \
        | RE_NO_BK_PARENS        | RE_NO_BK_REFS                             \
        | RE_NO_BK_VBAR          | RE_UNMATCHED_RIGHT_PAREN_ORD)

Collating Elements vs. Characters
=================================

POSIX generalizes the notion of a character to that of a collating element.  It defines a collating element to be ``a sequence of one or more bytes defined in the current collating sequence as a unit of collation.''

This generalizes the notion of a character in two ways.  First, a single character can map into two or more collating elements.  For example, the German ``es-zet'' collates as the collating element s followed by another collating element s.  Second, two or more characters can map into one collating element.  For example, the Spanish ll collates after l and before m.

Since POSIX's ``collating element'' preserves the essential idea of a ``character,'' we use the latter, more familiar, term in this document.

The Backslash Character
=======================

The \ character has one of four different meanings, depending on the context in which you use it and what syntax bits are set (see Syntax Bits).  It can: 1) stand for itself, 2) quote the next character, 3) introduce an operator, or 4) do nothing.

 1. It stands for itself inside a list (see List Operators) if the syntax bit RE_BACKSLASH_ESCAPE_IN_LISTS is not set.  For example, [\] would match \.

 2. It quotes (makes ordinary, if it's special) the next character when you use it either:

       * outside a list, (Sometimes you don't have to explicitly quote special characters to make them ordinary.  For instance, most characters lose any special meaning inside a list (see List Operators).  In addition, if the syntax bits RE_CONTEXT_INVALID_OPS and RE_CONTEXT_INDEP_OPS aren't set, then (for historical reasons) the matcher considers special characters ordinary if they are in contexts where the operations they represent make no sense; for example, then the match-zero-or-more operator (represented by *) matches itself in the regular expression *foo because there is no preceding expression on which it can operate.  It is poor practice, however, to depend on this behavior; if you want a special character to be ordinary outside a list, it's better to always quote it, regardless.) or

       * inside a list and the syntax bit RE_BACKSLASH_ESCAPE_IN_LISTS is set.

 3. It introduces an operator when followed by certain ordinary characters---sometimes only when certain syntax bits are set.  See the cases RE_BK_PLUS_QM, RE_NO_BK_BRACES, RE_NO_BK_VAR, RE_NO_BK_PARENS, RE_NO_BK_REF in Syntax Bits.  Also:

       * \b represents the match-word-boundary operator (see Match-word-boundary Operator).

       * \B represents the match-within-word operator (see Match-within-word Operator).

       * \< represents the match-beginning-of-word operator

          (see Match-beginning-of-word Operator).

       * \> represents the match-end-of-word operator (see Match-end-of-word Operator).

       * \w represents the match-word-constituent operator (see Match-word-constituent Operator).

       * \W represents the match-non-word-constituent operator (see Match-non-word-constituent Operator).

       * \` represents the match-beginning-of-buffer operator and \' represents the match-end-of-buffer operator (see Buffer Operators).

       * If Regex was compiled with the C preprocessor symbol emacs defined, then \sCLASS represents the match-syntactic-class operator and \SCLASS represents the match-not-syntactic-class operator (see Syntactic Class Operators).

 4. In all other cases, Regex ignores \.  For example, \n matches n.

Common Operators
****************

You compose regular expressions from operators.  In the following sections, we describe the regular expression operators specified by POSIX; GNU also uses these.  Most operators have more than one representation as characters.  See Regular Expression Syntax, for what characters represent what operators under what circumstances.

For most operators that can be represented in two ways, one representation is a single character and the other is that character preceded by \.  For example, either ( or \( represents the open-group operator.  Which one does depends on the setting of a syntax bit, in this case RE_NO_BK_PARENS.  Why is this so?  Historical reasons dictate some of the varying representations, while POSIX dictates others.

Finally, almost all characters lose any special meaning inside a list (see List Operators).

The Match-self Operator (ORDINARY CHARACTER)
============================================

This operator matches the character itself.  All ordinary characters (see Regular Expression Syntax) represent this operator.  For example, f is always an ordinary character, so the regular expression f matches only the string f.  In particular, it does not match the string ff.

The Match-any-character Operator (.)
====================================

This operator matches any single printing or nonprinting character except it won't match a:

newline
     if the syntax bit RE_DOT_NEWLINE isn't set.

null
     if the syntax bit RE_DOT_NOT_NULL is set.

The . (period) character represents this operator.  For example, a.b matches any three-character string beginning with a and ending with b.

The Concatenation Operator
==========================

This operator concatenates two regular expressions A and B. No character represents this operator; you simply put B after A.  The result is a regular expression that will match a string if A matches its first part and B matches the rest.  For example, xy (two match-self operators) matches xy.

Repetition Operators
====================

Repetition operators repeat the preceding regular expression a specified number of times.

The Match-zero-or-more Operator (*)
-----------------------------------

This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern. * represents this operator.  For example, o* matches any string made up of zero or more os.  Since this operator operates on the smallest preceding regular expression, fo* has a repeating o, not a repeating fo.  So, fo* matches f, fo, foo, and so on.

Since the match-zero-or-more operator is a suffix operator, it may be useless as such when no regular expression precedes it.  This is the case when it:

  * is first in a regular expression, or

  * follows a match-beginning-of-line, open-group, or alternation operator.

Three different things can happen in these cases:

 1. If the syntax bit RE_CONTEXT_INVALID_OPS is set, then the regular expression is invalid.

 2. If RE_CONTEXT_INVALID_OPS isn't set, but RE_CONTEXT_INDEP_OPS is, then * represents the match-zero-or-more operator (which then operates on the empty string).

 3. Otherwise, * is ordinary.

The matcher processes a match-zero-or-more operator by first matching as many repetitions of the smallest preceding regular expression as it can. Then it continues to match the rest of the pattern.

If it can't match the rest of the pattern, it backtracks (as many times as necessary), each time discarding one of the matches until it can either match the entire pattern or be certain that it cannot get a match.  For example, when matching ca*ar against caaar, the matcher first matches all three as of the string with the a* of the regular expression.  However, it cannot then match the final ar of the regular expression against the final r of the string.  So it backtracks, discarding the match of the last a in the string.  It can then match the remaining ar.

The Match-one-or-more Operator (+ or \+)
----------------------------------------

If the syntax bit RE_LIMITED_OPS is set, then Regex doesn't recognize this operator.  Otherwise, if the syntax bit RE_BK_PLUS_QM isn't set, then + represents this operator; if it is, then \+ does.

This operator is similar to the match-zero-or-more operator except that it repeats the preceding regular expression at least once; see Match-zero-or-more Operator, for what it operates on, how some syntax bits affect it, and how Regex backtracks to match it.

For example, supposing that + represents the match-one-or-more operator; then ca+r matches, e.g., car and caaaar, but not cr.

The Match-zero-or-one Operator (? or \?)
----------------------------------------

If the syntax bit RE_LIMITED_OPS is set, then Regex doesn't recognize this operator.  Otherwise, if the syntax bit RE_BK_PLUS_QM isn't set, then ? represents this operator; if it is, then \? does.

This operator is similar to the match-zero-or-more operator except that it repeats the preceding regular expression once or not at all; see Match-zero-or-more Operator, to see what it operates on, how some syntax bits affect it, and how Regex backtracks to match it.

For example, supposing that ? represents the match-zero-or-one operator; then ca?r matches both car and cr, but nothing else.

Interval Operators ({ ... } or \{ ... \})
-----------------------------------------

If the syntax bit RE_INTERVALS is set, then Regex recognizes interval expressions.  They repeat the smallest possible preceding regular expression a specified number of times.

If the syntax bit RE_NO_BK_BRACES is set, { represents the open-interval operator and } represents the close-interval operator ; otherwise, \{ and \} do.

Specifically, supposing that { and } represent the open-interval and close-interval operators; then:

{COUNT}
     matches exactly COUNT occurrences of the preceding regular expression.

{MIN,}
     matches MIN or more occurrences of the preceding regular expression.

{MIN, MAX}
     matches at least MIN but no more than MAX occurrences of the preceding regular expression.

The interval expression (but not necessarily the regular expression that contains it) is invalid if:

  * MIN is greater than MAX, or

  * any of COUNT, MIN, or MAX are outside the range zero to RE_DUP_MAX (which symbol regex.h defines).

If the interval expression is invalid and the syntax bit RE_NO_BK_BRACES is set, then Regex considers all the characters in the would-be interval to be ordinary.  If that bit isn't set, then the regular expression is invalid.

If the interval expression is valid but there is no preceding regular expression on which to operate, then if the syntax bit RE_CONTEXT_INVALID_OPS is set, the regular expression is invalid. If that bit isn't set, then Regex considers all the characters---other than backslashes, which it ignores---in the would-be interval to be ordinary.

The Alternation Operator (| or \|)
==================================

If the syntax bit RE_LIMITED_OPS is set, then Regex doesn't recognize this operator.  Otherwise, if the syntax bit RE_NO_BK_VBAR is set, then | represents this operator; otherwise, \| does.

Alternatives match one of a choice of regular expressions: if you put the character(s) representing the alternation operator between any two regular expressions A and B, the result matches the union of the strings that A and B match.  For example, supposing that | is the alternation operator, then foo|bar|quux would match any of foo, bar or quux.

The alternation operator operates on the largest possible surrounding regular expressions.  (Put another way, it has the lowest precedence of any regular expression operator.) Thus, the only way you can delimit its arguments is to use grouping.  For example, if ( and ) are the open and close-group operators, then fo(o|b)ar would match either fooar or fobar.  (foo|bar would match foo or bar.)

The matcher usually tries all combinations of alternatives so as to match the longest possible string.  For example, when matching (fooq|foo)*(qbarquux|bar) against fooqbarquux, it cannot take, say, the first (``depth-first'') combination it could match, since then it would be content to match just fooqbar.

Note that since the default behavior is to return the leftmost longest match, when more than one of a series of alternatives matches the actual match will be the longest matching alternative, not necessarily the first in the list.

List Operators ([ ... ] and [^ ... ])
=====================================

Lists, also called bracket expressions, are a set of one or more items.  An item is a character, a collating symbol, an equivalence class expression, a character class expression, or a range expression.  The syntax bits affect which kinds of items you can put in a list.  We explain the last four items in subsections below.  Empty lists are invalid.

A matching list matches a single character represented by one of the list items.  You form a matching list by enclosing one or more items within an open-matching-list operator (represented by [) and a close-list operator (represented by ]).

For example, [ab] matches either a or b. [ad]* matches the empty string and any string composed of just as and ds in any order.  Regex considers invalid a regular expression with a [ but no matching ].

Nonmatching lists are similar to matching lists except that they match a single character not represented by one of the list items.  You use an open-nonmatching-list operator (represented by [^ (Regex therefore doesn't consider the ^ to be the first character in the list.  If you put a ^ character first in (what you think is) a matching list, you'll turn it into a nonmatching list.)) instead of an open-matching-list operator to start a nonmatching list.

For example, [^ab] matches any character except a or b.

If the syntax bit RE_HAT_LISTS_NOT_NEWLINE is set, then nonmatching lists do not match a newline.

Most characters lose any special meaning inside a list.  The special characters inside a list follow.

]
     ends the list if it's not the first list item.  So, if you want to make the ] character a list item, you must put it first.

\
     quotes the next character if the syntax bit RE_BACKSLASH_ESCAPE_IN_LISTS is set.

[.
     represents the open-collating-symbol operator (see Collating Symbol Operators).

.]
     represents the close-collating-symbol operator.

[=
     represents the open-equivalence-class operator (see Equivalence Class Operators).

=]
     represents the close-equivalence-class operator.

[:
     represents the open-character-class operator (see Character Class Operators) if the syntax bit RE_CHAR_CLASSES is set and what follows is a valid character class expression.

:]
     represents the close-character-class operator if the syntax bit RE_CHAR_CLASSES is set and what precedes it is an open-character-class operator followed by a valid character class name.

-
     represents the range operator (see Range Operator) if it's not first or last in a list or the ending point of a range.

All other characters are ordinary.  For example, [.*] matches . and *.

Collating Symbol Operators ([. ... .])
--------------------------------------

Collating symbols can be represented inside lists. You form a collating symbol by putting a collating element between an open-collating-symbol operator and a close-collating-symbol operator.  [. represents the open-collating-symbol operator and .] represents the close-collating-symbol operator.  For example, if ll is a collating element, then [[.ll.]] would match ll.

Equivalence Class Operators ([= ... =])
---------------------------------------

Regex recognizes equivalence class expressions inside lists.  A equivalence class expression is a set of collating elements which all belong to the same equivalence class. You form an equivalence class expression by putting a collating element between an open-equivalence-class operator and a close-equivalence-class operator.  [= represents the open-equivalence-class operator and =] represents the close-equivalence-class operator.  For example, if a and A were an equivalence class, then both [[=a=]] and [[=A=]] would match both a and A.  If the collating element in an equivalence class expression isn't part of an equivalence class, then the matcher considers the equivalence class expression to be a collating symbol.

Character Class Operators ([: ... :])
-------------------------------------

If the syntax bit RE_CHAR_CLASSES is set, then Regex recognizes character class expressions inside lists.  A character class expression matches one character from a given class.  You form a character class expression by putting a character class name between an open-character-class operator (represented by [:) and a close-character-class operator (represented by :]). The character class names and their meanings are:

alnum
     letters and digits

alpha
     letters

blank
     system-dependent; for GNU, a space or tab

cntrl
     control characters (in the ASCII encoding, code 0177 and codes less than 040)

digit
     digits

graph
     same as print except omits space

lower
     lowercase letters

print
     printable characters (in the ASCII encoding, space tilde---codes 040 through 0176)

punct
     neither control nor alphanumeric characters

space
     space, carriage return, newline, vertical tab, and form feed

upper
     uppercase letters

xdigit
     hexadecimal digits: 0--9, a--f, A--F

These correspond to the definitions in the C library's <ctype.h> facility.  For example, [:alpha:] corresponds to the standard facility isalpha.  Regex recognizes character class expressions only inside of lists; so [[:alpha:]] matches any letter, but [:alpha:] outside of a bracket expression and not followed by a repetition operator matches just itself.

The Range Operator (-)
----------------------

Regex recognizes range expressions inside a list. They represent those characters that fall between two elements in the current collating sequence.  You form a range expression by putting a range operator between two of any of the following: characters, collating elements, collating symbols, and equivalence class expressions.  The starting point of the range and the ending point of the range don't have to be the same kind of item, e.g., the starting point could be a collating element and the ending point could be an equivalence class expression.  If a range's ending point is an equivalence class, then all the collating elements in that class will be in the range. (You can't use a character class for the starting or ending point of a range, since a character class is not a single character.) - represents the range operator.  For example, a-f within a list represents all the characters from a through f inclusively.

If the syntax bit RE_NO_EMPTY_RANGES is set, then if the range's ending point collates less than its starting point, the range (and the regular expression containing it) is invalid.  For example, the regular expression [z-a] would be invalid.  If this bit isn't set, then Regex considers such a range to be empty.

Since - represents the range operator, if you want to make a - character itself a list item, you must do one of the following:

  * Put the - either first or last in the list.

  * Include a range whose starting point collates strictly lower than - and whose ending point collates equal or higher.  Unless a range is the first item in a list, a - can't be its starting point, but can be its ending point.  That is because Regex considers - to be the range operator unless it is preceded by another -.  For example, in the ASCII encoding, ), *, +, ,, -, ., and / are contiguous characters in the collating sequence.  You might think that [)-+--/] has two ranges: )-+ and --/.  Rather, it has the ranges )-+ and +--, plus the character /, so it matches, e.g., ,, not ..

  * Put a range whose starting point is - first in the list.

For example, [-a-z] matches a lowercase letter or a hyphen (in English, in ASCII).

Grouping Operators (( ... ) or \( ... \))
=========================================

A group, also known as a subexpression, consists of an open-group operator, any number of other operators, and a close-group operator.  Regex treats this sequence as a unit, just as mathematics and programming languages treat a parenthesized expression as a unit.

Therefore, using groups, you can:

  * delimit the argument(s) to an alternation operator (see Alternation Operator) or a repetition operator (see Repetition Operators).

  * keep track of the indices of the substring that matched a given group. See Using Registers, for a precise explanation. This lets you:

       * use the back-reference operator (see Back-reference Operator).

       * use registers (see Using Registers).

If the syntax bit RE_NO_BK_PARENS is set, then ( represents the open-group operator and ) represents the close-group operator; otherwise, \( and \) do.

If the syntax bit RE_UNMATCHED_RIGHT_PAREN_ORD is set and a close-group operator has no matching open-group operator, then Regex considers it to match ).

The Back-reference Operator (\DIGIT)
====================================

If the syntax bit RE_NO_BK_REF isn't set, then Regex recognizes back references.  A back reference matches a specified preceding group. The back reference operator is represented by \DIGIT anywhere after the end of a regular expression's DIGIT-th group (see Grouping Operators).

DIGIT must be between 1 and 9.  The matcher assigns numbers 1 through 9 to the first nine groups it encounters.  By using one of \1 through \9 after the corresponding group's close-group operator, you can match a substring identical to the one that the group does.

Back references match according to the following (in all examples below, ( represents the open-group, ) the close-group, { the open-interval and } the close-interval operator):

  * If the group matches a substring, the back reference matches an identical substring.  For example, (a)\1 matches aa and (bana)na\1bo\1 matches bananabanabobana.  Likewise, (.*)\1 matches any (newline-free if the syntax bit RE_DOT_NEWLINE isn't set) string that is composed of two identical halves; the (.*) matches the first half and the \1 matches the second half.

  * If the group matches more than once (as it might if followed by, e.g., a repetition operator), then the back reference matches the substring the group last matched.  For example, ((a*)b)*\1\2 matches aabababa; first group 1 (the outer one) matches aab and group 2 (the inner one) matches aa.  Then group 1 matches ab and group 2 matches a.  So, \1 matches ab and \2 matches a.

  * If the group doesn't participate in a match, i.e., it is part of an alternative not taken or a repetition operator allows zero repetitions of it, then the back reference makes the whole match fail.  For example, (one()|two())-and-(three\2|four\3) matches one-and-three and two-and-four, but not one-and-four or two-and-three.  For example, if the pattern matches one-and-, then its group 2 matches the empty string and its group 3 doesn't participate in the match.  So, if it then matches four, then when it tries to back reference group 3---which it will attempt to do because \3 follows the four---the match will fail because group 3 didn't participate in the match.

You can use a back reference as an argument to a repetition operator.  For example, (a(b))\2* matches a followed by two or more bs.  Similarly, (a(b))\2{3} matches abbbb.

If there is no preceding DIGIT-th subexpression, the regular expression is invalid.

Anchoring Operators
===================

These operators can constrain a pattern to match only at the beginning or end of the entire string or at the beginning or end of a line.

The Match-beginning-of-line Operator (^)
----------------------------------------

This operator can match the empty string either at the beginning of the string or after a newline character.  Thus, it is said to anchor the pattern to the beginning of a line.

In the cases following, ^ represents this operator.  (Otherwise, ^ is ordinary.)

  * It (the ^) is first in the pattern, as in ^foo.

  * The syntax bit RE_CONTEXT_INDEP_ANCHORS is set, and it is outside a bracket expression.

  * It follows an open-group or alternation operator, as in a\(^b\) and a\|^b.  See Grouping Operators, and Alternation Operator.

These rules imply that some valid patterns containing ^ cannot be matched; for example, foo^bar if RE_CONTEXT_INDEP_ANCHORS is set.

If the not_bol field is set in the pattern buffer (see GNU Pattern Buffers), then ^ fails to match at the beginning of the string.  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.

The Match-end-of-line Operator ($)
----------------------------------

This operator can match the empty string either at the end of the string or before a newline character in the string.  Thus, it is said to anchor the pattern to the end of a line.

It is always represented by $.  For example, foo$ usually matches, e.g., foo and, e.g., the first three characters of foo\nbar.

Its interaction with the syntax bits and pattern buffer fields is exactly the dual of ^'s; see the previous section.  (That is, ``^'' becomes ``$'', ``beginning'' becomes ``end'', ``next'' becomes ``previous'', ``after'' becomes ``before'', and ``not_bol'' becomes ``not_eol''.)

GNU Operators
*************

Following are operators that GNU defines (and POSIX doesn't).

Word Operators
==============

The operators in this section require Regex to recognize parts of words. Regex uses a syntax table to determine whether or not a character is part of a word, i.e., whether or not it is word-constituent.

Non-Emacs Syntax Tables
-----------------------

A syntax table is an array indexed by the characters in your character set.  In the ASCII encoding, therefore, a syntax table has 256 elements.  Regex always uses a char * variable re_syntax_table as its syntax table.  In some cases, it initializes this variable and in others it expects you to initialize it.

  * If Regex is compiled with the preprocessor symbols emacs and SYNTAX_TABLE both undefined, then Regex allocates re_syntax_table and initializes an element I either to Sword (which it defines) if I is a letter, number, or _, or to zero if it's not.

  * If Regex is compiled with emacs undefined but SYNTAX_TABLE defined, then Regex expects you to define a char * variable re_syntax_table to be a valid syntax table.

  * See Emacs Syntax Tables, for what happens when Regex is compiled with the preprocessor symbol emacs defined.

The Match-word-boundary Operator (\b)
-------------------------------------

This operator (represented by \b) matches the empty string at either the beginning or the end of a word.  For example, \brat\b matches the separate word rat.

The Match-within-word Operator (\B)
-----------------------------------

This operator (represented by \B) matches the empty string within a word. For example, c\Brat\Be matches crate, but dirty \Brat doesn't match dirty rat.

The Match-beginning-of-word Operator (\<)
-----------------------------------------

This operator (represented by \<) matches the empty string at the beginning of a word.

The Match-end-of-word Operator (\>)
-----------------------------------

This operator (represented by \>) matches the empty string at the end of a word.

The Match-word-constituent Operator (\w)
----------------------------------------

This operator (represented by \w) matches any word-constituent character.

The Match-non-word-constituent Operator (\W)
--------------------------------------------

This operator (represented by \W) matches any character that is not word-constituent.

Buffer Operators
================

Following are operators which work on buffers.  In Emacs, a buffer is, naturally, an Emacs buffer.  For other programs, Regex considers the entire string to be matched as the buffer.

The Match-beginning-of-buffer Operator (\`)
-------------------------------------------

This operator (represented by \`) matches the empty string at the beginning of the buffer.

The Match-end-of-buffer Operator (\')
-------------------------------------

This operator (represented by \') matches the empty string at the end of the buffer.

GNU Emacs Operators
*******************

Following are operators that GNU defines (and POSIX doesn't) that you can use only when Regex is compiled with the preprocessor symbol emacs defined.

Syntactic Class Operators
=========================

The operators in this section require Regex to recognize the syntactic classes of characters.  Regex uses a syntax table to determine this.

Emacs Syntax Tables
-------------------

A syntax table is an array indexed by the characters in your character set.  In the ASCII encoding, therefore, a syntax table has 256 elements.

If Regex is compiled with the preprocessor symbol emacs defined, then Regex expects you to define and initialize the variable re_syntax_table to be an Emacs syntax table.  Emacs' syntax tables are more complicated than Regex's own (see Non-Emacs Syntax Tables).  See Syntax (The GNU Emacs User's Manual), for a description of Emacs' syntax tables.

The Match-syntactic-class Operator (\sCLASS)
--------------------------------------------

This operator matches any character whose syntactic class is represented by a specified character.  \sCLASS represents this operator where CLASS is the character representing the syntactic class you want.  For example, w represents the syntactic class of word-constituent characters, so \sw matches any word-constituent character.

The Match-not-syntactic-class Operator (\SCLASS)
------------------------------------------------

This operator is similar to the match-syntactic-class operator except that it matches any character whose syntactic class is not represented by the specified character.  \SCLASS represents this operator.  For example, w represents the syntactic class of word-constituent characters, so \Sw matches any character that is not word-constituent.

What Gets Matched?
******************

Regex usually matches strings according to the ``leftmost longest'' rule; that is, it chooses the longest of the leftmost matches.  This does not mean that for a regular expression containing subexpressions that it simply chooses the longest match for each subexpression, left to right; the overall match must also be the longest possible one.

For example, (ac*)(c*d[ac]*)\1 matches acdacaaa, not acdac, as it would if it were to choose the longest match for the first subexpression.

Programming with Regex
**********************

Here we describe how you use the Regex data structures and functions in C programs.  Regex has three interfaces: one designed for GNU, one compatible with POSIX (as specified by POSIX, draft 1003.2/D11.2), and one compatible with Berkeley UNIX.  The POSIX interface is not documented here; see the documentation of GNU libc, or the POSIX man pages.  The Berkeley UNIX interface is documented here for convenience, since its documentation is not otherwise readily available on GNU systems.

GNU Regex Functions
===================

If you're writing code that doesn't need to be compatible with either POSIX or Berkeley UNIX, you can use these functions.  They provide more options than the other interfaces.

GNU Pattern Buffers
-------------------

To compile, match, or search for a given regular expression, you must supply a pattern buffer.  A pattern buffer holds one compiled regular expression. (Regular expressions are also referred to as ``patterns,'' hence the name ``pattern buffer.'')

You can have several different pattern buffers simultaneously, each holding a compiled pattern for a different regular expression.

regex.h defines the pattern buffer struct with the following public fields:

       unsigned char *buffer;
       unsigned long allocated;
       char *fastmap;
       char *translate;
       size_t re_nsub;
       unsigned no_sub : 1;
       unsigned not_bol : 1;
       unsigned not_eol : 1;

GNU Regular Expression Compiling
--------------------------------

In GNU, you can both match and search for a given regular expression.  To do either, you must first compile it in a pattern buffer (see GNU Pattern Buffers).

Regular expressions match according to the syntax with which they were compiled; with GNU, you indicate what syntax you want by setting the variable re_syntax_options (declared in regex.h) before calling the compiling function, re_compile_pattern (see below).  See Syntax Bits, and Predefined Syntaxes.

You can change the value of re_syntax_options at any time. Usually, however, you set its value once and then never change it.

re_compile_pattern takes a pattern buffer as an argument.  You must initialize the following fields:

translate initialization

translate
     Initialize this to point to a translate table if you want one, or to zero if you don't.  We explain translate tables in GNU Translate Tables.

fastmap
     Initialize this to nonzero if you want a fastmap, or to zero if you don't.

buffer
allocated
     If you want re_compile_pattern to allocate memory for the compiled pattern, set both of these to zero.  If you have an existing block of memory (allocated with malloc) you want Regex to use, set buffer to its address and allocated to its size (in bytes).

     re_compile_pattern uses realloc to extend the space for the compiled pattern as necessary.

To compile a pattern buffer, use:

     char *
     re_compile_pattern (const char *REGEX, const int REGEX_SIZE,
                         struct re_pattern_buffer *PATTERN_BUFFER)

REGEX is the regular expression's address, REGEX_SIZE is its length, and PATTERN_BUFFER is the pattern buffer's address.

If re_compile_pattern successfully compiles the regular expression, it returns zero and sets *PATTERN_BUFFER to the compiled pattern.  It sets the pattern buffer's fields as follows:

buffer
     to the compiled pattern.

syntax
     to the current value of re_syntax_options.

re_nsub
     to the number of subexpressions in REGEX.

If re_compile_pattern can't compile REGEX, it returns an error string corresponding to a POSIX error code.

GNU Matching
------------

Matching the GNU way means trying to match as much of a string as possible starting at a position within it you specify.  Once you've compiled a pattern into a pattern buffer (see GNU Regular Expression Compiling), you can ask the matcher to match that pattern against a string using:

     int
     re_match (struct re_pattern_buffer *PATTERN_BUFFER,
               const char *STRING, const int SIZE,
               const int START, struct re_registers *REGS)

PATTERN_BUFFER is the address of a pattern buffer containing a compiled pattern.  STRING is the string you want to match; it can contain newline and null characters.  SIZE is the length of that string.  START is the string index at which you want to begin matching; the first character of STRING is at index zero. See Using Registers, for an explanation of REGS; you can safely pass zero.

re_match matches the regular expression in PATTERN_BUFFER against the string STRING according to the syntax of PATTERN_BUFFER.  (see GNU Regular Expression Compiling, for how to set it.)  The function returns -1 if the compiled pattern does not match any part of STRING and -2 if an internal error happens; otherwise, it returns how many (possibly zero) characters of STRING the pattern matched.

An example: suppose PATTERN_BUFFER points to a pattern buffer containing the compiled pattern for a*, and STRING points to aaaaab (whereupon SIZE should be 6). Then if START is 2, re_match returns 3, i.e., a* would have matched the last three as in STRING.  If START is 0, re_match returns 5, i.e., a* would have matched all the as in STRING.  If START is either 5 or 6, it returns zero.

If START is not between zero and SIZE, then re_match returns -1.

GNU Searching
-------------

Searching means trying to match starting at successive positions within a string.  The function re_search does this.

Before calling re_search, you must compile your regular expression.  See GNU Regular Expression Compiling.

Here is the function declaration:

     int
     re_search (struct re_pattern_buffer *PATTERN_BUFFER,
                const char *STRING, const int SIZE,
                const int START, const int RANGE,
                struct re_registers *REGS)

whose arguments are the same as those to re_match (see GNU Matching) except that the two arguments START and RANGE replace re_match's argument START.

If RANGE is positive, then re_search attempts a match starting first at index START, then at START + 1 if that fails, and so on, up to START + RANGE; if RANGE is negative, then it attempts a match starting first at index START, then at START -1 if that fails, and so on.

If START is not between zero and SIZE, then re_search returns -1.  When RANGE is positive, re_search adjusts RANGE so that START + RANGE - 1 is between zero and SIZE, if necessary; that way it won't search outside of STRING.  Similarly, when RANGE is negative, re_search adjusts RANGE so that START + RANGE + 1 is between zero and SIZE, if necessary.

If the fastmap field of PATTERN_BUFFER is zero, re_search matches starting at consecutive positions; otherwise, it uses fastmap to make the search more efficient. See Searching with Fastmaps.

If no match is found, re_search returns -1.  If a match is found, it returns the index where the match began.  If an internal error happens, it returns -2.

Matching and Searching with Split Data
--------------------------------------

Using the functions re_match_2 and re_search_2, you can match or search in data that is divided into two strings.

The function:

     int
     re_match_2 (struct re_pattern_buffer *BUFFER,
                 const char *STRING1, const int SIZE1,
                 const char *STRING2, const int SIZE2,
                 const int START,
                 struct re_registers *REGS,
                 const int STOP)

is similar to re_match (see GNU Matching) except that you pass two data strings and sizes, and an index STOP beyond which you don't want the matcher to try matching.  As with re_match, if it succeeds, re_match_2 returns how many characters of STRING it matched.  Regard STRING1 and STRING2 as concatenated when you set the arguments START and STOP and use the contents of REGS; re_match_2 never returns a value larger than SIZE1 + SIZE2.

The function:

     int
     re_search_2 (struct re_pattern_buffer *BUFFER,
                  const char *STRING1, const int SIZE1,
                  const char *STRING2, const int SIZE2,
                  const int START, const int RANGE,
                  struct re_registers *REGS,
                  const int STOP)

is similarly related to re_search.

Searching with Fastmaps
-----------------------

If you're searching through a long string, you should use a fastmap. Without one, the searcher tries to match at consecutive positions in the string.  Generally, most of the characters in the string could not start a match.  It takes much longer to try matching at a given position in the string than it does to check in a table whether or not the character at that position could start a match.  A fastmap is such a table.

More specifically, a fastmap is an array indexed by the characters in your character set.  Under the ASCII encoding, therefore, a fastmap has 256 elements.  If you want the searcher to use a fastmap with a given pattern buffer, you must allocate the array and assign the array's address to the pattern buffer's fastmap field.  You either can compile the fastmap yourself or have re_search do it for you; when fastmap is nonzero, it automatically compiles a fastmap the first time you search using a particular compiled pattern.

By setting the buffer’s fastmap field before calling re_compile_pattern, you can reuse a buffer data structure across multiple searches with different patterns, and allocate the fastmap only once.  Nonetheless, the fastmap must be recompiled each time the buffer has a new pattern compiled into it.

To compile a fastmap yourself, use:

     int
     re_compile_fastmap (struct re_pattern_buffer *PATTERN_BUFFER)

PATTERN_BUFFER is the address of a pattern buffer.  If the character C could start a match for the pattern, re_compile_fastmap makes PATTERN_BUFFER->fastmap[C] nonzero.  It returns 0 if it can compile a fastmap and -2 if there is an internal error.  For example, if | is the alternation operator and PATTERN_BUFFER holds the compiled pattern for a|b, then re_compile_fastmap sets fastmap['a'] and fastmap['b'] (and no others).

re_search uses a fastmap as it moves along in the string: it checks the string's characters until it finds one that's in the fastmap. Then it tries matching at that character.  If the match fails, it repeats the process.  So, by using a fastmap, re_search doesn't waste time trying to match at positions in the string that couldn't start a match.

If you don't want re_search to use a fastmap, store zero in the fastmap field of the pattern buffer before calling re_search.

Once you've initialized a pattern buffer's fastmap field, you need never do so again---even if you compile a new pattern in it---provided the way the field is set still reflects whether or not you want a fastmap.  re_search will still either do nothing if fastmap is null or, if it isn't, compile a new fastmap for the new pattern.

GNU Translate Tables
--------------------

If you set the translate field of a pattern buffer to a translate table, then the GNU Regex functions to which you've passed that pattern buffer use it to apply a simple transformation to all the regular expression and string characters at which they look.

A translate table is an array indexed by the characters in your character set.  Under the ASCII encoding, therefore, a translate table has 256 elements.  The array's elements are also characters in your character set.  When the Regex functions see a character C, they use translate[C] in its place, with one exception: the character after a \ is not translated.  (This ensures that, the operators, e.g., \B and \b, are always distinguishable.)

For example, a table that maps all lowercase letters to the corresponding uppercase ones would cause the matcher to ignore differences in case. (A table that maps all uppercase letters to the corresponding lowercase ones would work just as well for this purpose.)  Such a table would map all characters except lowercase letters to themselves, and lowercase letters to the corresponding uppercase ones.  Under the ASCII encoding, here's how you could initialize such a table (we'll call it case_fold):

     for (i = 0; i < 256; i++)
       case_fold[i] = i;
     for (i = 'a'; i <= 'z'; i++)
       case_fold[i] = i - ('a' - 'A');

You tell Regex to use a translate table on a given pattern buffer by assigning that table's address to the translate field of that buffer.  If you don't want Regex to do any translation, put zero into this field.  You'll get weird results if you change the table's contents anytime between compiling the pattern buffer, compiling its fastmap, and matching or searching with the pattern buffer.

Using Registers
---------------

A group in a regular expression can match a (possibly empty) substring of the string that regular expression as a whole matched.  The matcher remembers the beginning and end of the substring matched by each group.

To find out what they matched, pass a nonzero REGS argument to a GNU matching or searching function (see GNU Matching and GNU Searching), i.e., the address of a structure of this type, as defined in regex.h:

     struct re_registers
     {
       unsigned num_regs;
       regoff_t *start;
       regoff_t *end;
     };

Except for (possibly) the NUM_REGS'th element (see below), the Ith element of the start and end arrays records information about the Ith group in the pattern.  (They're declared as C pointers, but this is only because not all C compilers accept zero-length arrays; conceptually, it is simplest to think of them as arrays.)

The start and end arrays are allocated in one of two ways. The simplest and perhaps most useful is to let the matcher (re)allocate enough space to record information for all the groups in the regular expression.  If re_set_registers is not called before searching or matching, then the matcher allocates two arrays each of 1 + RE_NSUB elements (RE_NSUB is another field in the pattern buffer; see GNU Pattern Buffers).  The extra element is set to -1.  Then on subsequent calls with the same pattern buffer and REGS arguments, the matcher reallocates more space if necessary.

The function:

     void
     re_set_registers (struct re_pattern_buffer *BUFFER,
     			      struct re_registers *REGS,
     			      size_t NUM_REGS,
     			      regoff_t *STARTS, regoff_t *ENDS)

sets REGS to hold NUM_REGS registers, storing them in STARTS and ENDS.  Subsequent matches using BUFFER and REGS will use this memory for recording register information.  STARTS and ENDS must be allocated with malloc, and must each be at least NUM_REGS * sizeof (regoff_t) bytes long.

If NUM_REGS is zero, then subsequent matches should allocate their own register data.

Unless this function is called, the first search or match using BUFFER will allocate its own register data, without freeing the old data.

The following examples illustrate the information recorded in the re_registers structure.  (In all of them, ( represents the open-group and ) the close-group operator.  The first character in the string STRING is at index 0.)

  * If the regular expression has an I-th group that matches a substring of STRING, then the function sets REGS->start[I] to the index in STRING where the substring matched by the I-th group begins, and REGS->end[I] to the index just beyond that substring's end.  The function sets REGS->start[0] and REGS->end[0] to analogous information about the entire pattern.

     For example, when you match ((a)(b)) against ab, you get:

       * 0 in REGS->start[0] and 2 in REGS->end[0]

       * 0 in REGS->start[1] and 2 in REGS->end[1]

       * 0 in REGS->start[2] and 1 in REGS->end[2]

       * 1 in REGS->start[3] and 2 in REGS->end[3]

  * If a group matches more than once (as it might if followed by, e.g., a repetition operator), then the function reports the information about what the group last matched.

     For example, when you match the pattern (a)* against the string aa, you get:

       * 0 in REGS->start[0] and 2 in REGS->end[0]

       * 1 in REGS->start[1] and 2 in REGS->end[1]

  * If the I-th group does not participate in a successful match, e.g., it is an alternative not taken or a repetition operator allows zero repetitions of it, then the function sets REGS->start[I] and REGS->end[I] to -1.

     For example, when you match the pattern (a)*b against the string b, you get:

       * 0 in REGS->start[0] and 1 in REGS->end[0]

       * -1 in REGS->start[1] and -1 in REGS->end[1]

  * If the I-th group matches a zero-length string, then the function sets REGS->start[I] and REGS->end[I] to the index just beyond that zero-length string.

     For example, when you match the pattern (a*)b against the string b, you get:

       * 0 in REGS->start[0] and 1 in REGS->end[0]

       * 0 in REGS->start[1] and 0 in REGS->end[1]

  * If an I-th group contains a J-th group in turn not contained within any other group within group I and the function reports a match of the I-th group, then it records in REGS->start[J] and REGS->end[J] the last match (if it matched) of the J-th group.

     For example, when you match the pattern ((a*)b)* against the string abb, group 2 last matches the empty string, so you get what it previously matched:

       * 0 in REGS->start[0] and 3 in REGS->end[0]

       * 2 in REGS->start[1] and 3 in REGS->end[1]

       * 2 in REGS->start[2] and 2 in REGS->end[2]

     When you match the pattern ((a)*b)* against the string abb, group 2 doesn't participate in the last match, so you get:

       * 0 in REGS->start[0] and 3 in REGS->end[0]

       * 2 in REGS->start[1] and 3 in REGS->end[1]

       * 0 in REGS->start[2] and 1 in REGS->end[2]

  * If an I-th group contains a J-th group in turn not contained within any other group within group I and the function sets REGS->start[I] and REGS->end[I] to -1, then it also sets REGS->start[J] and REGS->end[J] to -1.

     For example, when you match the pattern ((a)*b)*c against the string c, you get:

       * 0 in REGS->start[0] and 1 in REGS->end[0]

       * -1 in REGS->start[1] and -1 in REGS->end[1]

       * -1 in REGS->start[2] and -1 in REGS->end[2]

Freeing GNU Pattern Buffers
---------------------------

To free any allocated fields of a pattern buffer, use the POSIX function regfree:

     void
     regfree (regex_t *PREG)

PREG is the pattern buffer whose allocated fields you want freed; this works because since the type regex_t---the type for POSIX pattern buffers---is equivalent to the type re_pattern_buffer.

regfree also sets PREG's allocated field to zero. After a buffer has been freed, it must have a regular expression compiled in it before passing it to a matching or searching function.

BSD Regex Functions
===================

If you're writing code that has to be Berkeley UNIX compatible, you'll need to use these functions whose interfaces are the same as those in Berkeley UNIX.

BSD Regular Expression Compiling
--------------------------------

With Berkeley UNIX, you can only search for a given regular expression; you can't match one.  To search for it, you must first compile it.  Before you compile it, you must indicate the regular expression syntax you want it compiled according to by setting the variable re_syntax_options (declared in regex.h to some syntax (see Regular Expression Syntax).

To compile a regular expression use:

     char *
     re_comp (char *REGEX)

REGEX is the address of a null-terminated regular expression. re_comp uses an internal pattern buffer, so you can use only the most recently compiled pattern buffer.  This means that if you want to use a given regular expression that you've already compiled---but it isn't the latest one you've compiled---you'll have to recompile it.  If you call re_comp with the null string (not the empty string) as the argument, it doesn't change the contents of the pattern buffer.

If re_comp successfully compiles the regular expression, it returns zero.  If it can't compile the regular expression, it returns an error string.  re_comp's error messages are identical to those of re_compile_pattern (see GNU Regular Expression Compiling).

BSD Searching
-------------

Searching the Berkeley UNIX way means searching in a string starting at its first character and trying successive positions within it to find a match.  Once you've compiled a pattern using re_comp (see BSD Regular Expression Compiling), you can ask Regex to search for that pattern in a string using:

     int
     re_exec (char *STRING)

STRING is the address of the null-terminated string in which you want to search.

re_exec returns either 1 for success or 0 for failure.  It automatically uses a GNU fastmap (see Searching with Fastmaps).