NAME
regexp - Match a regular expression against a string
SYNOPSIS
regexp ?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...?
DESCRIPTION
-nocase
-indices
--
DIFFERENT FLAVORS OF REs
REGULAR EXPRESSION SYNTAX
BRACKET EXPRESSIONS
ESCAPES
METASYNTAX
b
c
e
i
m
n
p
q
s
t
w
x
CHOOSING AMONG ALTERNATIVE MATCHES
BASIC REGULAR EXPRESSIONS
LIMITS AND BACKWARD COMPATIBILITY
KEYWORDS

NAME

regexp - Match a regular expression against a string

SYNOPSIS

regexp ?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...?

DESCRIPTION

Determines whether the regular expression exp matches part or all of string and returns 1 if it does, 0 if it doesn't.

If additional arguments are specified after string then they are treated as the names of variables in which to return information about which part(s) of string matched exp. MatchVar will be set to the range of string that matched all of exp. The first subMatchVar will contain the characters in string that matched the leftmost parenthesized subexpression within exp, the next subMatchVar will contain the characters that matched the next parenthesized subexpression to the right in exp, and so on.

If the initial arguments to regexp start with - then they are treated as switches. The following switches are currently supported:

-nocase
Causes upper-case characters in string to be treated as lower case during the matching process.

-indices
Changes what is stored in the subMatchVars. Instead of storing the matching characters from string, each variable will contain a list of two decimal strings giving the indices in string of the first and last characters in the matching range of characters.

--
Marks the end of switches. The argument following this one will be treated as exp even if it starts with a -.

If there are more subMatchVar's than parenthesized subexpressions within exp, or if a particular subexpression in exp doesn't match the string (e.g. because it was in a portion of the expression that wasn't matched), then the corresponding subMatchVar will be set to ``-1 -1'' if -indices has been specified or to an empty string otherwise.

DIFFERENT FLAVORS OF REs

Regular expressions (``RE''s), as defined by POSIX, come in two flavors: extended REs (roughly those of egrep), ``EREs'', and basic REs (roughly those of ed), ``BREs''. This implementation adds a third flavor, advanced REs, ``AREs'', that offer a syntax for specifying BREs and EREs. The following primarily describes AREs.

BREs mostly exist for backward compatibility in some old programs; they will be discussed at the end. POSIX EREs are almost an exact subset of AREs;

REGULAR EXPRESSION SYNTAX

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 branches, separated by `|'. It matches anything that matches any of the branches.

A branch is zero or more items, concatenated. It matches a match for the first, followed by a match for the second, etc; an empty branch matches the empty string.

An item is an atom possibly followed by a single quantifier: `*', `+', `?', or a bound. An atom followed by `*' matches a sequence of 0 or more matches of the atom. An atom followed by `+' matches a sequence of 1 or more matches of the atom. An atom followed by `?' matches a sequence of 0 or 1 matches of the atom.

A bound is `{' followed by an unsigned decimal integer, possibly followed by `,' possibly followed by another unsigned decimal integer, always followed by `}'. The integers must lie between 0 and 255 inclusive, and if there are two of them, the first may not exceed the second. An atom followed by a bound containing one integer i and no comma matches a sequence of exactly i matches of the atom. An atom followed by a bound containing one integer i and a comma matches a sequence of i or more matches of the atom. An atom followed by a bound containing two integers i and j matches a sequence of i through j (inclusive) matches of the atom.

A quantifier followed by `?' (that is, `*?', `+?', `??', `{...}?') is a non-greedy quantifier, which matches the same possibilities, but prefers the smallest number rather than the largest number of matches.

An atom is a regular expression enclosed in `()' (matching a match for the regular expression, with the match noted for possible reporting), an empty set of `()' (matching an empty string, again noted for possible reporting), either form with the leading parenthesis replaced by `(?:' (``non-capturing parentheses'', as opposed to the plainer ``capturing'' form; they have the same matching semantics but do no reporting), a bracket expression (see next section), `.' (matching any single character), a constraint (see below), a `\' followed by any non-alphanumeric character (matching that character taken as an ordinary character, e.g. `\\' matches a backslash character), an escape (see later section) beginning with `\' followed by an alphanumeric character, or a single character with no other significance (matching that character).

A constraint matches an empty string when specific conditions are met. (Some more constraints are described later.) `^' matches at the beginning of a line, and `$' matches at the end of a line; these constraints are also known as anchors. A regular expression enclosed in `(?=' and `)' (positive lookahead) matches at any point where a string matching that regular expression begins. A regular expression enclosed in `(?!' and `)' (negative lookahead) matches at any point where a string not matching that regular expression begins. Lookahead constraints may not contain back references (see later), and all parentheses within them are treated as non-capturing. A constraint may not be followed by a quantifier.

A `{' followed by a character other than a digit is an ordinary character, not the beginning of a bound. An RE may not end with an `\'.

BRACKET EXPRESSIONS

A bracket expression is a list of characters enclosed in `[]'. It normally matches any single character from the list (but see below). If the list begins with `^', it matches any single character (but see below) not from the rest of the list. If two characters in the list are separated by `-', this is shorthand for the full range of characters between those two (inclusive) in the collating sequence, e.g. `[0-9]' in ASCII matches any decimal digit. Two ranges may not share an endpoint, e.g. `a-c-e'. Ranges are very collating-sequence-dependent, and portable programs should avoid relying on them.

To include a literal `]' in the list, make it the first character (following a possible `^'), or precede it with `\'. To include a literal `-', make it the first or last character, or the second endpoint of a range, or precede it with `\'. To use a literal `-' as the first endpoint of a range, enclose it in `[.' and `.]' to make it a collating element (see below), or precede it with `\'. With the exception of these, some combinations using `[' (see next paragraphs), and escapes, all other special characters lose their special significance within a bracket expression.

Within a bracket expression, a collating element (a character, a multi-character sequence that collates as if it were a single character, or a collating-sequence name for either) enclosed in `[.' and `.]' stands for the sequence of characters of that collating element. The sequence is a single element of the bracket expression's list. A bracket expression in a locale which has multi-character collating elements can thus match more than one character. Most insidiously, if `^' is used, this can happen even if no collating elements appear in the bracket expression! If the collating sequence includes a `ch' collating element, then the RE `[[.ch.]]*c' matches the first five characters of `chchcc', and the RE `[^c]b' matches all of `chb'.

Within a bracket expression, a collating element enclosed in `[=' and `=]' is an equivalence class, standing for the sequences of characters of all collating elements equivalent to that one, including itself. (If there are no other equivalent collating elements, the treatment is as if the enclosing delimiters were `[.' and `.]'.) For example, if o and #92;o'o^' are the members of an equivalence class, then `[[=o=]]', `[[=#92;o'o^'=]]', and `[o#92;o'o^']' are all synonymous. An equivalence class may not be an endpoint of a range.

Within a bracket expression, the name of a character class enclosed in `[:' and `:]' stands for the list of all characters belonging to that class. Standard character class names are:

alnum digit punct alpha graph space blank lower upper cntrl print xdigit

These stand for the character classes defined in ctype(3). A locale may provide others. A character class may not be used as an endpoint of a range.

There are two special cases of bracket expressions: the bracket expressions `[[:<:]]' and `[[:>:]]' are constraints, matching empty strings at the beginning and end of a word respectively. A word is defined as a sequence of word characters which is neither preceded nor followed by word characters. A word character is an alnum character (as defined by ctype(3)) or an underscore. This is an extension, and its use is deprecated; users of AREs should use constraint escapes instead (see below).

ESCAPES

Escapes, which begin with a `\' followed by an alphanumeric character, come in several varieties: character entry, class shorthands, constraint, and back references. 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 character, and inside a bracket expression, `\' is an ordinary character. (The latter is the one actual incompatibility between POSIX and AREs.)

Character-entry escapes exist to make it easier to specify non-printing and otherwise inconvenient characters in REs. The Standard C escapes are all available. is ``ESC'', or failing that, the character with octal value 033. applications where there are multiple levels of backslash processing).

low-order 5 bits are the same as those of X, and whose other bits are all zero. represent the characters whose octal values are 0, 0XY, and 0XYZ respectively. (See below for why `\X' isn't in the list here.) represents the character whose hexadecimal value is 0xHHH (a single character no matter how many hexadecimal digits are used). represents the Unicode character U+WXYZ in the local byte ordering. is reserved for a somewhat-hypothetical Unicode extension to 32 bits.

The character-entry escapes are always taken as ordinary characters. For example, `\135' is `]' in ASCII, but `\135' does not terminate a bracket expression. Beware, however, that some applications - e.g., C compilers-interpret such sequences themselves before the regular-expression package gets to see them.

Class-shorthand escapes provide shorthands for certain commonly-used character classes. `[[:digit:]]', `[[:space:]]', and `[[:alnum:]_]' respectively (note the underscore in `\w'). the complementary classes: `[^[:digit:]]', `[^[:space:]]', and `[^[:alnum:]_]' respectively. Within bracket expressions, `[:digit:]', `[:space:]', and `[:alnum:]_' respectively;

A constraint escape is a constraint, matching the empty string if specific conditions are met, written as an escape. (see MATCHING, below, for how they differ from `^' and `$'). A word is defined as in the specification of [[:<:]] and [[:>:]] above. Constraint escapes are illegal within bracket expressions.

A back reference is of the form `\M', where M is a nonzero digit (1-9), or `\MNN', where MNN is some number of digits (first 1-9, rest 0-9) and the value MNN is not greater than the number of closing capturing parentheses seen so far. A back reference 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 subexpressions.

There is an inherent historical ambiguity between octal character-entry escapes and back references, which is resolved by heuristics. A single non-zero digit, not followed by another digit, is always taken as a back reference. A leading zero always indicates an octal escape. 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. These are extensions, compatible with but not specified by POSIX.

Normally the flavor of RE being used is specified by application-dependent means. However, this can be overridden by a director. 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 embedded options: the sequence `(?xyz)', where xyz is one or more alphabetic characters, specifies options affecting the rest of the RE. These supplement, and can override, options specified by the application in application-specific ways. 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)

In addition to the usual (tight) RE syntax, in which all characters are significant, there is an expanded syntax, available in all flavors of RE by application-specified option, or in AREs by embedded x option. In the expanded syntax, any white-space character not preceded by `\' and not within a bracket expression is ignored, so a complex RE can be paragraphed legibly. There is one exception: white space is not allowed within multi-character symbols like the ARE `(?:' or the BRE `\('. White-space characters are blank, tab, newline, etc. - any character defined as space by ctype(3). In addition, all characters between a non-backslashed non-bracket-expression `#' and the following newline (or the end of the RE) are ignored, so comments can be inserted conveniently. Exactly how a multi-line expanded-syntax RE can be entered by a user, if at all, is application-specific; this is primarily a programming facility.

Finally, in an ARE, outside bracket expressions, the sequence `(?#ttt)', where ttt 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.

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

CHOOSING AMONG ALTERNATIVE MATCHES

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, it matches the longest. Subexpressions also match the longest possible substrings, subject to the constraint that the whole match be as long as possible, with subexpressions starting earlier in the RE taking priority over ones starting later. Note that higher-level subexpressions thus take priority over their lower-level component subexpressions.

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 characters of `weeknights', when `(.*).*' is matched against `abc' the parenthesized subexpression matches all three characters, 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, e.g. `x' becomes `[xX]'. When it appears inside a bracket expression, all case counterparts of it are added to the bracket expression, so that (e.g.) `[x]' becomes `[xX]' and `[^x]' becomes `[^xX]'.

If newline-sensitive matching is specified, and the string supplied for matching contains newlines, `.' and complemented bracket expressions (`[^...]') will never match the newline character, and `^' and `$' will match the empty string after and before a newline respectively, in addition to matching at beginning and end of string respectively. ARE `\A' and `\Z' continue to match beginning or end of string only.

If partial newline-sensitive matching is specified, this affects `.' and complemented bracket expressions as with newline-sensitive matching, but not `^' and `$'.

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

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 themselves 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 (but no other escapes) are available.

LIMITS AND BACKWARD COMPATIBILITY

No particular limit is imposed on the length of REs or the number paired parentheses, brackets, or braces.

In AREs, a `\' inside [...] is an escape, so a literal `\' within `[]' must be written `\\'.

In AREs, some escapes mean special things in a bracket expression (i.e. `\d', `\s', `\w') and others are illegal (i.e. `\D', `\S',

In AREs, a `{' followed by a digit will not match those two characters but will instead start a bound. Such sequences should be rare, and will often result in an error because following characters will not look like a valid bound.

In AREs, a `\' followed by an alphanumeric character is either an escape or an error. A bunch of new escapes were treated as literal characters in old versions of Tcl.

The longest-leftmost match is found in AREs. Old versions of Tcl found the first-leftmost match. This may affect some old REs which were written in the expectation that the first match would be reported. The careful crafting of old REs to optimize the search order for fast matching is obsolete. AREs examine all possible matches in parallel, and their performance is largely insensitive to their complexity, but cases where the search order was exploited to deliberately find a match which was not the longest will need rewriting.

KEYWORDS

match, regular expression, string
Copyright © 1998 Sun Microsystems, Inc.
Copyright © 1995-1997 Roger E. Critchlow Jr.