Tcl Source Code

Artifact [06540f6ee7]
Login

Artifact 06540f6ee7186c7fb35eb4358bfa48b6d4f2d426:

Attachment "re_syntax_fmt.txt" to ticket [2903743fff] added by lvirden 2009-11-25 21:09:31.
Reformatting page.  Please Wait... done
Tcl                   Tcl Built-In Commands          re_syntax(n)
______________________________________________________________________



NAME
     re_syntax - Syntax of Tcl regular expressions
_________________________________________________________________



DESCRIPTION
     A _r_e_g_u_l_a_r _e_x_p_r_e_s_s_i_o_n describes strings of characters.  It's a
     pattern that matches certain strings and does not match others.



DIFFERENT FLAVORS OF REs
     Regular expressions (``RE''s), as defined by POSIX, come in two
     flavors: _e_x_t_e_n_d_e_d REs (``ERE''s) and _b_a_s_i_c REs (``BRE''s).  EREs
     are roughly those of the traditional _e_g_r_e_p, while BREs are
     roughly those of the traditional _e_d. This implementation adds a
     third flavor, _a_d_v_a_n_c_e_d REs (``ARE''s), basically EREs with some
     significant extensions.

     This manual page primarily describes AREs. BREs mostly exist for
     backward compatibility in some old programs; they will be dis-
     cussed at the end. POSIX EREs are almost an exact subset of AREs.
     Features of AREs that are not present in EREs will be indicated.



REGULAR EXPRESSION SYNTAX
     Tcl regular expressions are implemented using the package written
     by Henry Spencer, based on the 1003.2 spec and some (not quite
     all) of the Perl5 extensions (thanks, Henry!). Much of the
     description of regular expressions below is copied verbatim from
     his manual entry.

     An ARE is one or more _b_r_a_n_c_h_e_s, separated by ``|'', matching any-
     thing that matches any of the branches.

     A branch is zero or more _c_o_n_s_t_r_a_i_n_t_s or _q_u_a_n_t_i_f_i_e_d _a_t_o_m_s, con-
     catenated.  It matches a match for the first, followed by a match
     for the second, etc; an empty branch matches the empty string.



QUANTIFIERS
     A quantified atom is an _a_t_o_m possibly followed by a single _q_u_a_n_-
     _t_i_f_i_e_r.  Without a quantifier, it matches a single match for the
     atom.  The quantifiers, and what a so-quantified atom matches,
     are:

       *     a sequence of 0 or more matches of the atom

       +     a sequence of 1 or more matches of the atom

       ?     a sequence of 0 or 1 matches of the atom

       {_m}   a sequence of exactly _m matches of the atom

       {_m,}  a sequence of _m or more matches of the atom

       {_m,_n} a sequence of _m through _n (inclusive) matches of the
             atom; _m may not exceed _n

       *?  +?  ??  {_m}?  {_m,}?  {_m,_n}?
             _n_o_n-_g_r_e_e_d_y quantifiers, which match the same possibili-
             ties, but prefer the smallest number rather than the
             largest number of matches (see MATCHING)

     The forms using { and } are known as _b_o_u_n_ds. The numbers _m and _n
     are unsigned decimal integers with permissible values from 0 to
     255 inclusive.



ATOMS
     An atom is one of:

       (_r_e)  matches a match for _r_e (_r_e is any regular expression)
             with the match noted for possible reporting

       (?:_r_e)
             as previous, but does no reporting (a ``non-capturing''
             set of parentheses)

       ()    matches an empty string, noted for possible reporting

       (?:)  matches an empty string, without reporting

       [_c_h_a_r_s]
             a _b_r_a_c_k_e_t _e_x_p_r_e_s_s_i_o_n, matching any one of the _c_h_a_r_s (see
             BRACKET EXPRESSIONS for more detail)

       .     matches any single character

       \_k    matches the non-alphanumeric character _k taken as an
             ordinary character, e.g. \\ matches a backslash character

       \_c    where _c is alphanumeric (possibly followed by other char-
             acters), an _e_s_c_a_p_e (AREs only), see ESCAPES below

       {     when followed by a character other than a digit, matches
             the left-brace character ``{''; when followed by a digit,
             it is the beginning of a _b_o_u_n_d (see above)

       _x     where _x is a single character with no other significance,
             matches that character.



CONSTRAINTS
     A _c_o_n_s_t_r_a_i_n_t matches an empty string when specific conditions are
     met. A constraint may not be followed by a quantifier. The simple
     constraints are as follows; some more constraints are described
     later, under ESCAPES.

       ^       matches at the beginning of a line9
                                                 ar=e]]t'h'e, maenmdbe`r`s[oo]f''
     aanreeqaulilvaslyennocneymcoluass.s,Antheeqnui`v`a[l[e=noc=e]]c'l'a,ss``m[a[y=not be an endpoint9
       $       matches at the end of a line9
     of a range.
9       (?=_r_e)  _p_o_s_i_t_i_v_e _l_o_o_k_a_h_e_a_d (AREs only), matches at any point9
          (_N_o_t_e: Tcl implements only the Unicode locale. It does not9
               where a substring matching _r_e begins9
          define any equivalence classes. The examples above are just
          illustrations.)9
       (?!_r_e)  _n_e_g_a_t_i_v_e _l_o_o_k_a_h_e_a_d (AREs only), matches at any point
               where no substring matching _r_e begins

     The lookahead constraints may not contain back references (see9
ESCAPES9
     later), and all parentheses within them are considered non-9
     Escapes (AREs only), which begin with a \ followed by an9
     capturing.9
     alphanumeric character, come in several varieties: character
     entry, class shorthands, constraint escapes, and back references.9
     An RE may not end with ``\''.9
     A \ followed by an alphanumeric character but not constituting a
     valid escape is illegal in AREs. In EREs, there are no escapes:
     outside a bracket expression, a \ followed by an alphanumeric
     character merely stands for that character as an ordinary charac-9
BRACKET EXPRESSIONS9
     ter, and inside a bracket expression, \ is an ordinary character.9
     A _b_r_a_c_k_e_t _e_x_p_r_e_s_s_i_o_n is a list of characters enclosed in ``[]''.9
     (The latter is the one actual incompatibility between EREs and9
     It normally matches any single character from the list (but see9
     AREs.)9
     below). If the list begins with ``^'', it matches any single
     character (but see below) _n_o_t from the rest of the list.

     If two characters in the list are separated by ``-'', this is9
CHARACTER-ENTRY ESCAPES9
     shorthand for the full _r_a_n_g_e of characters between those two9
     Character-entry escapes (AREs only) exist to make it easier to9
     (inclusive) in the collating sequence, e.g.  ``[0-9]'' in Unicode9
     specify non-printing and otherwise inconvenient characters in9
     matches any conventional decimal digit. Two ranges may not share9
     REs:9
     an endpoint, so e.g.  ``a-c-e'' is illegal. Ranges in Tcl always
     use the Unicode collating sequence, but other programs may use9
       \a   alert (bell) character, as in C9
     other collating sequences and this can be a source of incompata-
     bility between programs.9
       \b   backspace, as in C
9     To include a literal ] or - in the list, the simplest method is9
       \B   synonym for \ to help reduce backslash doubling in some9
     to enclose it in [. and .] to make it a collating element (see9
            applications where there are multiple levels of backslash9
     below). Alternatively, make it the first character (following a9
            processing9
     possible ``^''), or (AREs only) precede it with ``\''.  Alterna-
     tively, for ``-'', make it the last character, or the second end-9
       \c_X  (where _X is any character) the character whose low-order 59
     point of a range. To use a literal - as the first endpoint of a9
            bits are the same as those of _X, and whose other bits are9
     range, make it a collating element or (AREs only) precede it with9
            all zero9
     ``\''.  With the exception of these, some combinations using [
     (see next paragraphs), and escapes, all other special characters9
       \e   the character whose collating-sequence name is ``ESC'', or9
     lose their special significance within a bracket expression.9
            failing that, the character with octal value 033

       \f   formfeed, as in C
9CHARACTER CLASSES9
       \n   newline, as in C9
     Within a bracket expression, the name of a _c_h_a_r_a_c_t_e_r _c_l_a_s_s
     enclosed in [: and :] stands for the list of all characters (not9
       \r   carriage return, as in C9
     all collating elements!) belonging to that class.  Standard char-
     acter classes are:9
       \t   horizontal tab, as in C
9     alpha   A letter.9
       \u_w_x_y_z
            (where _w_x_y_z is exactly four hexadecimal digits) the9
     upper   An upper-case letter.9
            Unicode character U+_w_x_y_z in the local byte ordering
9     lower   A lower-case letter.9
       \U_s_t_u_v_w_x_y_z
            (where _s_t_u_v_w_x_y_z is exactly eight hexadecimal digits)9
     digit   A decimal digit.9
            reserved for a somewhat-hypothetical Unicode extension to
            32 bits9
     xdigit  A hexadecimal digit.
9       \v   vertical tab, as in C are all available.9
     alnum   An alphanumeric (letter or digit).
9       \x_h_h_h9
     print   A "printable" (same as graph, except also including9
            (where _h_h_h is any sequence of hexadecimal digits) the9
             space).9
            character whose hexadecimal value is 0x_h_h_h (a single char-
            acter no matter how many hexadecimal digits are used).9
     blank   A space or tab character.
9       \0   the character whose value is 09
     space   A character producing white space in displayed text.
9       \_x_y  (where _x_y is exactly two octal digits, and is not a _b_a_c_k9
     punct   A punctuation character.9
            _r_e_f_e_r_e_n_c_e (see below)) the character whose octal value is
            0_x_y9
     graph   A character with a visible representation (includes both
             alnum and punct).9
       \_x_y_z (where _x_y_z is exactly three octal digits, and is not a
            back reference (see below)) the character whose octal9
     cntrl   A control character.9
            value is 0_x_y_z
9     A locale may provide others. A character class may not be used as9
     Hexadecimal digits are ``0''-``9'', ``a''-``f'', and ``A''-``F''.9
     an endpoint of a range.9
     Octal digits are ``0''-``7''.
9          (_N_o_t_e: the current Tcl implementation has only one locale,9
     The character-entry escapes are always taken as ordinary charac-9
          the Unicode locale, which supports exactly the above9
     ters.  For example, \135 is ] in Unicode, but \135 does not ter-9
          classes.)9
     minate a bracket expression. Beware, however, that some applica-
     tions (e.g., C compilers and the Tcl interpreter if the regular
     expression is not quoted with braces) interpret such sequences
     themselves before the regular-expression package gets to see9
BRACKETED CONSTRAINTS9
     them, which may require doubling (quadrupling, etc.) the ``\''.9
     There are two special cases of bracket expressions: the bracket
     expressions ``[[:<:]]''  and ``[[:>:]]''  are constraints, match-
     ing empty strings at the beginning and end of a word respec-
     tively.  A word is defined as a sequence of word characters that9
CLASS-SHORTHAND ESCAPES9
     is neither preceded nor followed by word characters. A word char-9
     Class-shorthand escapes (AREs only) provide shorthands for cer-9
     acter is an _a_l_n_u_m character or an underscore (``_'').  These spe-9
     tain commonly-used character classes:9
     cial bracket expressions are deprecated; users of AREs should use
     constraint escapes instead (see below).9
       \d        [[:digit:]]

       \s        [[:space:]]
9COLLATING ELEMENTS9
       \w        [[:alnum:]_] (note underscore)9
     Within a bracket expression, a collating element (a character, a
     multi-character sequence that collates as if it were a single9
       \D        [^[:digit:]]9
     character, or a collating-sequence name for either) enclosed in
     [. and .] stands for the sequence of characters of that collating9
       \S        [^[:space:]]9
     element. The sequence is a single element of the bracket
     expression's list. A bracket expression in a locale that has9
       \W        [^[:alnum:]_] (note underscore)9
     multi-character collating elements can thus match more than one
     character. So (insidiously), a bracket expression that starts9
     Within bracket expressions, ``\d'', ``\s'', and ``\w'' lose their9
     with ^ can match multi-character collating elements even if none9
     outer brackets, and ``\D'', ``\S'', and ``\W'' are illegal. (So,9
     of them appear in the bracket expression!9
     for example, ``[a-c\d]'' is equivalent to ``[a-c[:digit:]]''.
     Also, ``[a-c\D]'', which is equivalent to ``[a-c^[:digit:]]'', is9
          (_N_o_t_e: Tcl has no multi-character collating elements. This9
     illegal.)9
          information is only for illustration.)

     For example, assume the collating sequence includes a ch multi-
     character collating element. Then the RE ``[[.ch.]]*c'' (zero or9
CONSTRAINT ESCAPES9
     more ``chs'' followed by ``c'') matches the first five characters9
     A constraint escape (AREs only) is a constraint, matching the9
     of ``chchcc''.  Also, the RE ``[^c]b'' matches all of ``chb''9
     empty string if specific conditions are met, written as an9
     (because ``[^c]'' matches the multi-character ``ch'').9
     escape:

       \A    matches only at the beginning of the string (see MATCH-
             ING, below, for how this differs from ``^'')9
EQUIVALENCE CLASSES
     Within a bracket expression, a collating element enclosed in [=9
       \m    matches only at the beginning of a word9
     and =] is an equivalence class, standing for the sequences of
     characters of all collating elements equivalent to that one,9
       \M    matches only at the end of a word9
     including itself. (If there are no other equivalent collating
     elements, the treatment is as if the enclosing delimiters were9
       \y    matches only at the beginning or end of a word9
     ``[.'' and ``.]''.)  For example, if o and
9       \Y    matches only at a point that is not the beginning or end
             of a word

       \Z    matches only at the end of the string (see MATCHING,
             below, for how this differs from ``$'')

       \_m    (where _m is a nonzero digit) a _b_a_c_k _r_e_f_e_r_e_n_c_e, see below

       \_m_n_n  (where _m is a nonzero digit, and _n_n is some more digits,
             and the decimal value _m_n_n is not greater than the number
             of closing capturing parentheses seen so far) a _b_a_c_k
             _r_e_f_e_r_e_n_c_e, see below

     A word is defined as in the specification of ``[[:<:]]''  and
     ``[[:>:]]''  above. Constraint escapes are illegal within bracket
     expressions.



BACK REFERENCES
     A back reference (AREs only) matches the same string matched by
     the parenthesized subexpression specified by the number, so that
     (e.g.)  ``([bc])\1'' matches ``bb'' or ``cc'' but not ``bc''.
     The subexpression must entirely precede the back reference in the
     RE.  Subexpressions are numbered in the order of their leading
     parentheses.  Non-capturing parentheses do not define subexpres-
     sions.

     There is an inherent historical ambiguity between octal
     character-entry escapes and back references, which is resolved by
     heuristics, as hinted at above. A leading zero always indicates
     an octal escape. A single non-zero digit, not followed by another
     digit, is always taken as a back reference. A multi-digit
     sequence not starting with a zero is taken as a back reference if
     it comes after a suitable subexpression (i.e. the number is in
     the legal range for a back reference), and otherwise is taken as
     octal.



METASYNTAX
     In addition to the main syntax described above, there are some
     special forms and miscellaneous syntactic facilities available.

     Normally the flavor of RE being used is specified by
     application-dependent means. However, this can be overridden by a
     _d_i_r_e_c_t_o_r. If an RE of any flavor begins with ``***:'', the rest
     of the RE is an ARE. If an RE of any flavor begins with ``***='',
     the rest of the RE is taken to be a literal string, with all
     characters considered ordinary characters.

     An ARE may begin with _e_m_b_e_d_d_e_d _o_p_t_i_o_n_s: a sequence (?_x_y_z) (where
     _x_y_z is one or more alphabetic characters) specifies options
     affecting the rest of the RE. These supplement, and can override,
     any options specified by the application. The available option
     letters are:

       b  rest of RE is a BRE

       c  case-sensitive matching (usual default)

       e  rest of RE is an ERE

       i  case-insensitive matching (see MATCHING, below)

       m  historical synonym for n

       n  newline-sensitive matching (see MATCHING, below)

       p  partial newline-sensitive matching (see MATCHING, below)

       q  rest of RE is a literal (``quoted'') string, all ordinary
          characters

       s  non-newline-sensitive matching (usual default)

       t  tight syntax (usual default; see below)

       w  inverse partial newline-sensitive (``weird'') matching (see
          MATCHING, below)

       x  expanded syntax (see below)

     Embedded options take effect at the ) terminating the sequence.
     They are available only at the start of an ARE, and may not be
     used later within it.

     In addition to the usual (_t_i_g_h_t) RE syntax, in which all charac-
     ters are significant, there is an _e_x_p_a_n_d_e_d syntax, available in
     all flavors of RE with the -expanded switch, or in AREs with the
     embedded x option. In the expanded syntax, white-space characters
     are ignored and all characters between a # and the following new-
     line (or the end of the RE) are ignored, permitting paragraphing
     and commenting a complex RE. There are three exceptions to that
     basic rule:

     +o  a white-space character or ``#'' preceded by ``\'' is retained

     +o  white space or ``#'' within a bracket expression is retained

     +o  white space and comments are illegal within multi-character
        symbols like the ARE ``(?:''  or the BRE ``\(''

     Expanded-syntax white-space characters are blank, tab, newline,
     and any character that belongs to the _s_p_a_c_e character class.

     Finally, in an ARE, outside bracket expressions, the sequence
     ``(?#_t_t_t)'' (where _t_t_t is any text not containing a ``)'') is a
     comment, completely ignored. Again, this is not allowed between
     the characters of multi-character symbols like ``(?:''.  Such
     comments are more a historical artifact than a useful facility,
     and their use is deprecated; use the expanded syntax instead.

     _N_o_n_e of these metasyntax extensions is available if the applica-
     tion (or an initial ``***='' director) has specified that the
     user's input be treated as a literal string rather than as an RE.



MATCHING
     In the event that an RE could match more than one substring of a
     given string, the RE matches the one starting earliest in the
     string. If the RE could match more than one substring starting at
     that point, its choice is determined by its _p_r_e_f_e_r_e_n_c_e: either
     the longest substring, or the shortest.

     Most atoms, and all constraints, have no preference. A
     parenthesized RE has the same preference (possibly none) as the
     RE. A quantified atom with quantifier {_m} or {_m}? has the same
     preference (possibly none) as the atom itself. A quantified atom
     with other normal quantifiers (including {_m,_n} with _m equal to _n)
     prefers longest match. A quantified atom with other non-greedy
     quantifiers (including {_m,_n}?  with _m equal to _n) prefers shor-
     test match. A branch has the same preference as the first quanti-
     fied atom in it which has a preference. An RE consisting of two
     or more branches connected by the | operator prefers longest
     match.

     Subject to the constraints imposed by the rules for matching the
     whole RE, subexpressions also match the longest or shortest pos-
     sible substrings, based on their preferences, with subexpressions
     starting earlier in the RE taking priority over ones starting
     later. Note that outer subexpressions thus take priority over
     their component subexpressions.

     Note that the quantifiers {1,1} and {1,1}? can be used to force
     longest and shortest preference, respectively, on a subexpression
     or a whole RE.

     Match lengths are measured in characters, not collating elements.
     An empty string is considered longer than no match at all. For
     example, ``bb*'' matches the three middle characters of
     ``abbbc'', ``(week|wee)(night|knights)'' matches all ten charac-
     ters of ``weeknights'', when ``(.*).*''  is matched against
     ``abc'' the parenthesized subexpression matches all three charac-
     ters, and when ``(a*)*'' is matched against ``bc'' both the whole
     RE and the parenthesized subexpression match an empty string.

     If case-independent matching is specified, the effect is much as
     if all case distinctions had vanished from the alphabet. When an
     alphabetic that exists in multiple cases appears as an ordinary
     character outside a bracket expression, it is effectively
     transformed into a bracket expression containing both cases, so
     that x becomes ``[xX]''.  When it appears inside a bracket
     expression, all case counterparts of it are added to the bracket
     expression, so that ``[x]'' becomes ``[xX]'' and ``[^x]'' becomes
     ``[^xX]''.

     If newline-sensitive matching is specified, . and bracket expres-
     sions using ^ will never match the newline character (so that
     matches will never cross newlines unless the RE explicitly
     arranges it) and ^ and $ will match the empty string after and
     before a newline respectively, in addition to matching at begin-
     ning and end of string respectively. ARE \A and \Z continue to
     match beginning or end of string _o_n_l_y.

     If partial newline-sensitive matching is specified, this affects
     but not ^ and $.

     If inverse partial newline-sensitive matching is specified, this
     affects ^ and $ as with newline-sensitive matching, but not . and
     bracket expressions. This is not very useful but is provided for
     symmetry.



LIMITS AND COMPATIBILITY
     No particular limit is imposed on the length of REs. Programs
     intended to be highly portable should not employ REs longer than
     256 bytes, as a POSIX-compliant implementation can refuse to
     accept such REs.

     The only feature of AREs that is actually incompatible with POSIX
     EREs is that \ does not lose its special significance inside
     bracket expressions. All other ARE features use syntax which is
     illegal or has undefined or unspecified effects in POSIX EREs;
     the *** syntax of directors likewise is outside the POSIX syntax
     for both BREs and EREs.

     Many of the ARE extensions are borrowed from Perl, but some have
     been changed to clean them up, and a few Perl extensions are not
     present.  Incompatibilities of note include ``\b'', ``\B'', the
     lack of special treatment for a trailing newline, the addition of
     complemented bracket expressions to the things affected by
     newline-sensitive matching, the restrictions on parentheses and
     back references in lookahead constraints, and the
     longest/shortest-match (rather than first-match) matching seman-
     tics.

     The matching rules for REs containing both normal and non-greedy
     quantifiers have changed since early beta-test versions of this
     package. (The new rules are much simpler and cleaner, but do not
     work as hard at guessing the user's real intentions.)

     Henry Spencer's original 1986 _r_e_g_e_x_p package, still in widespread
     use (e.g., in pre-8.1 releases of Tcl), implemented an early ver-
     sion of today's EREs. There are four incompatibilities between
     _r_e_g_e_x_p's near-EREs (``RREs'' for short) and AREs. In roughly
     increasing order of significance:

     +o  In AREs, \ followed by an alphanumeric character is either an
        escape or an error, while in RREs, it was just another way of
        writing the alphanumeric. This should not be a problem because
        there was no reason to write such a sequence in RREs.

     +o  { followed by a digit in an ARE is the beginning of a bound,
        while in RREs, { was always an ordinary character. Such
        sequences should be rare, and will often result in an error
        because following characters will not look like a valid bound.

     +o  In AREs, \ remains a special character within ``[]'', so a
        literal \ within [] must be written ``\\''.  \\ also gives a
        literal \ within [] in RREs, but only truly paranoid program-
        mers routinely doubled the backslash.

     +o  AREs report the longest/shortest match for the RE, rather than
        the first found in a specified search order. This may affect
        some RREs which were written in the expectation that the first
        match would be reported. (The careful crafting of RREs to
        optimize the search order for fast matching is obsolete (AREs
        examine all possible matches in parallel, and their perfor-
        mance is largely insensitive to their complexity) but cases
        where the search order was exploited to deliberately find a
        match which was _n_o_t the longest/shortest will need rewriting.)



BASIC REGULAR EXPRESSIONS
     BREs differ from EREs in several respects.  ``|'', ``+'', and ?
     are ordinary characters and there is no equivalent for their
     functionality. The delimiters for bounds are \{ and ``\}'', with
     { and } by themselves ordinary characters. The parentheses for
     nested subexpressions are \( and ``\)'', with ( and ) by them-
     selves ordinary characters. ^ is an ordinary character except at
     the beginning of the RE or the beginning of a parenthesized
     subexpression, $ is an ordinary character except at the end of
     the RE or the end of a parenthesized subexpression, and * is an
     ordinary character if it appears at the beginning of the RE or
     the beginning of a parenthesized subexpression (after a possible
     leading ``^'').  Finally, single-digit back references are avail-
     able, and \< and \> are synonyms for ``[[:<:]]''  and ``[[:>:]]''
     respectively; no other escapes are available.



SEE ALSO
     RegExp(3), regexp(n), regsub(n), lsearch(n), switch(n), text(n)




KEYWORDS
     match, regular expression, string

modified 8.1                                         re_syntax(n)


















































9