Hosted by |
|
Tcl 8.1 now handles advanced regular expressions (REs). Previous regular
expression handling is almost unchanged except that clumsy handling
of escapes like Note that a few advanced features aren't useful yet but are ready for future Tcl releases. That's because Tcl 8.1 (apart from the regular expression engine) implements only the Unicode locale (where all characters sort in Unicode order, there are no multi-character collating elements and no equivalence classes). This document has an overview of the new regular expression features. For exact semantics and more details, see the new re_syntax(n) reference page. (The re_syntax(n) page was split from the 8.1 regexp(n) reference page, which used to cover RE syntax for all Tcl commands.) This howto document covers: 1. Regular Expression Overview
2. Regular Expressions in Tcl 8.1
3. Summary: Regular Expression changes in Tcl 8.1 Part 1. Regular Expression OverviewThis Part describes regular expressions (REs), explains REs from Tcl 8.0 and before, and describes the Tcl regexp and regsub commands. Part Two describes the new Tcl 8.1 REs. What are Regular Expressions?A regular expression, or RE, describes strings of characters (words or phrases or any arbitrary text). It's a pattern that matches certain strings and doesn't match others. For example, you could write an RE to tell you if a string contains a URL (World Wide Web Uniform Resource Locator, such as http://somehost/somefile.html). Regular expressions can be either broad and general or focused and precise.
A regular expression uses metacharacters
(characters that assume special meaning for matching other characters)
such as Regular Expressions in Tcl 8.0 and BeforeRegular expressions in Tcl 8.0 and before had the following metacharacters:
The syntax above is supported in Tcl 8.1. Tcl 8.1 also supports advanced regular expressions (AREs). These powerful expressions are introduced in more detail in Part Two. Briefly, though, AREs support backreferences, lookahead, non-greedy matching, many escapes, features that are useful for internationalization (handling collation elements, equivalence classes and character classes), and much more. The Tcl 8.1 regular expression engine almost always interprets 8.0-style REs correctly. In the few cases that it doesn't, and when the problem is too difficult to fix, the 8.1 engine has an option to select 8.0 ("ERE") interpretation. Overview of regexp and regsubThe Tcl commands regexp and regsub use regular expressions:
Backslash ProcessingIf you've used Tcl, you probably recognize the\t in the
previous example as a character-entry escape that stands
for a tab character.
We actually used the 8.1 syntax above; the example wouldn't have
worked under 8.0!
In Tcl 8.0 and before, you had to surround the regular expression
with double quotes so the Tcl backslash processor could convert the
For more about the simplified 8.1 syntax, see the section Backslash Escapes. Part 2. Regular Expressions in Tcl 8.1Tcl 8.1 regular expressions are basically a superset of 8.0 REs. This howto document has an overview of the new features. Please see the re_syntax(n) reference page for exact semantics and more details. Non-Greedy QuantifiersA quantifier specifies "how many." For example, the quantifier*
in the RE z* matches zero or more zs. By default, regular
expression quantifiers are greedy:
they match as much text as they can. Tcl 8.1 REs also have non-greedy
quantifiers, which match the least text they can.
To make a non-greedy quantifier, add a question mark (? ) at the end.
Let's start by storing some HTML text in a variable, then using two regexp commands to match it. The first RE is greedy, and the second is non-greedy:
The first RE <EM>.*</EM> is "greedy."
It matches from the first <EM>
to the last </EM> .
The second RE <EM>.*?</EM> , with
a question mark (? ) after the * quantifier, is
non-greedy: it matches as little text as possible after the first
<EM> .
Could you write a greedy RE that works like the non-greedy version?
It isn't easy!
A greedy RE like <EM>[^<]*</EM>
would do it in this case -- but it wouldn't work if there were other
HTML tags (with a < character) between the pair of
<EM> tags in the $x string.
Here are a new string and another pair of REs to match it:
The greedy RE 3z* matches all the zs it can
(three) under its "zero or more" rule.
The non-greedy RE 3z*? matches just 3 because it matches
the fewest zs it can under its "zero or more" rule.
To review, the greedy quantifiers from Tcl 8.0 are: Backslash EscapesA backslash (\ ) disables the metacharacter after it. For example,
a\* matches the character a followed by a literal asterisk
(* ) character. In Tcl 8.0 and before, it was legal to put
a backslash before a non-metacharacter -- for instance,
regexp {\p} matched the character p. (Note that
regexp {\n}
matched the character n, which was a source of confusion. To
get a newline character into an RE before version 8.1, you had to write
regexp "\n"
so Tcl processing inside double quotes would convert the \n
to a newline.)
The Tcl 8.1 regular expression engine interprets backslash escapes
itself. So now
One of the most important changes in 8.1 is that a backslash inside a
bracket expression is treated as the start of an escape.
In 8.0 and before, a backslash inside brackets was treated as a literal
backslash character.
For example, in 8.0 and before,
Tcl 8.1 has also added many new backslash escapes. For instance,
In Tcl 8.1 regular expressions (but not in other parts of the
language), it's illegal
to use a backslash before a non-metacharacter unless it makes a valid
escape. So
As explained above, the Tcl 8.1 regular expression engine now interprets
backslash sequences like
Finally, remember that (as in Tcl 8.0 and before) some applications, such as C compilers, interpret these backslash sequences themselves before the regular expression engine sees them. You may need to double (or quadruple, etc.) the number of backslashes for these applications. Still, in straight Tcl 8.1 code, writing backslash escapes is now both simpler and more powerful than in 8.0 and before. BoundsYou've seen the quantifiers* , + , and ? .
They specify "how many" (respectively, zero or more, one or more, and
zero or one). Tcl 8.1 added new quantifiers that let you choose exactly
how many matches: the bounds operators, {} .
These operators
come in three greedy forms:
Character ClassesA character class is a name for one or more characters. For example,punct stands for the "punctuation" characters.
A character class is always written as part of a bracket
expression, which is a list of characters enclosed in [] .
For instance, the character class named The table below describes the Tcl 8.1 character classes.
You can use more than one character class in a bracket expression.
You can also mix character classes with ranges and single characters.
For instance,
The advantage of character classes (like Tcl 8.1 has a standard set of character classes that are defined in the source code file generic/regc_locale.c. Tcl 8.1 has one locale defined: the Unicode locale. It may support other locales (and other character classes) in the future. Collating ElementsA collating symbol lets you represent other characters unambiguously. A collating symbol is written surrounded by brackets and dots, like[.number-sign.]
Collating symbols
must be written in a bracket expression (inside [] ).
So [[.number-sign.]] will match the character # , as
you can see here:
Tcl 8.1 has a standard set of collating symbols that are
defined in the source code file generic/regc_locale.c.
Note: Tcl 8.1 does not implement multi-character collating
elements like ch
(which is the fourth character in the Spanish alphabet
a, b, c, ch, d, e,
f, g, h, i...)
So the examples below are not supported in Tcl 8.1,
but are here for completeness.
(Future versions of Tcl may have multi-character collating elements.)
Suppose ch and c sort next to each other in your dialect, and ch is treated as an atomic character. The example bracket expression below uses two collating symbols. It matches one or more of ch and c. But it doesn't match an h standing alone:
Here's one tricky and surprising thing about collating symbols.
A caret at the start of a bracket expression ([^... )
means that, in a locale with multi-character collating elements,
the symbol can match more than one character. For instance,
the RE in the example below matches any character
other than c, followed by the character b. So the
expression matches all of chb:
Again, the two previous examples are not supported in Tcl 8.1,
but are here for completeness.
Equivalence ClassesAn equivalence class is written as part of a bracket expression, like[[=c=]] .
It's any collating element that has the same relative order in
the collating sequence as c.
Note: Tcl 8.1 only implements the Unicode locale. It doesn't define any equivalence classes. So, although the Tcl regular expression engine supports equivalence classes, the examples below are not supported in Tcl 8.1. (Future versions of Tcl may define equivalence classes.)
Let's imagine that both of the characters A and a
fall at the same place in the collating sequence;
they belong to the same equivalence class.
In that case, both of the bracket expressions Noncapturing SubpatternsThere are two reasons to put parentheses around all or part of an RE. One is to make a quantifier (like* or + ) apply
to the parenthesized part. For instance, the RE Oh,( no!)+
would match Oh, no! as well as Oh, no! no!
and so on.
The other reason to use parentheses is that they capture the
matched text. Captured text is used in
back references,
in "matching" variables in the regexp command, as well as in the
regsub command.
If you don't want parentheses to capture text, add
Lookahead AssertionsThere are times you'd like to be able to test for a pattern without including that text in the match. For instance, you might want to match the protocol in a URL (like http or ftp), but only if that URL ends with .com. Or maybe you want to match the protocol only if the URL does not end with .edu. In cases like those, you'd like to "look ahead" and see how the URL ends. A lookahead assertion is handy here.
A positive lookahead has the form
The regular expressions above may seem complicated, but they're
really not bad! Find the lookahead expression in the first
regexp command above; it starts with
(?= and ends at the corresponding parenthesis. The "guts" of this
lookahead expression is .*\.com$ , which stands for "a string
that ends with .com". So the first regexp command
above matches any string containing non-colon (: )
characters, as long as the rest of the string ends with .com.
The second regexp is similar but looks for a string ending
with .edu.
Because regexp returns 0, you can see that this doesn't match.
The third regexp looks for a string not ending with .edu.
It matches because $x ends with .com.
Tcl 8.1 lets you document complex regular expressions by embedding comments. See the next section. SwitchesTcl 8.1 added command switches to regexp and regsub. For a complete list, see the commands' reference pages. Let's look at two of the most important changes.
Complex REs can be difficult to document. The
-expanded switch sets expanded syntax, which
lets you add comments within a regular expression. Comments start with
a
In expanded syntax, you can use space and tab characters to indent and
make your code clear.
To enter actual space and tab characters into your RE, use the escapes
\s and
\t , respectively.
The other important new switch we'll cover here is -line.
It enables newline-sensitive matching.
By default (without -line), Tcl regular expressions have always
treated newlines as an ordinary character.
For example, if a string contains several lines (separated by
newline characters), the end-of-string anchor
With the -line switch, the metacharacters
The -line switch actually enables two other switches.
You can set part of the features from -line by choosing
one of these switches instead:
The -lineanchor switch makes
^ and
$ match at the beginning and end of a line.
The -linestop switch makes
. and
[] stop matching at a newline character.
Options, DirectorsThis section introduces two more features from Tcl 8.1. Details are in the re_syntax(n) reference page.
An 8.1 RE can start with embedded options. These look like
An RE can also start with three asterisks, which is a director.
For example, Part 3. Summary: Regular Expression Changes in Tcl 8.1Tcl 8.1 added advanced regular expression syntax. The new re_syntax(n) reference page has details.This table below summarizes the new syntax:
Some of the new switches for regexp and regsub are:
|