Phantom for Windows v1.7 Users Guide - Copyright © 2006 P1 Systems Incorporated. All Rights Reserved.

Prev | Next | Users Guide | PhantomScript Reference | P1 Systems




Regular Expressions

The following Phantom for Windows statements accept a regular expression as an argument.
RegExMatch
RegExGrep
RegExReplace
RegExSplit
Regular expressions provide a very powerful pattern matching capability. Phantom for Windows supports Perl-style regular expressions. Regular expressions can be confusing at first and we recommend spending some time learning about them if you have a need for sophisticated pattern matching in your Phantom scripts.

Phantom's regular expression support is provided by the PCRE library package, which is open source software, written by Philip Hazel, and copyright by the University of Cambridge, England.

Sources can be downloaded from ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/.

The following is from the PCRE Library documentation.

PCRE REGULAR EXPRESSION DETAILS


The syntax and semantics of the regular expressions supported by PCRE
are described below. Regular expressions are also described in the Perl
documentation and in a number of other books, some of which have copi-
ous examples. Jeffrey Friedl's "Mastering Regular Expressions", pub-
lished by O'Reilly, covers them in great detail. The description here
is intended as reference documentation.

The basic operation of PCRE is on strings of bytes. However, there is
also support for UTF-8 character strings. To use this support you must
build PCRE to include UTF-8 support, and then call pcre_compile() with
the PCRE_UTF8 option. How this affects the pattern matching is men-
tioned in several places below. There is also a summary of UTF-8 fea-
tures in the section on UTF-8 support in the main pcre page.

A regular expression is a pattern that is matched against a subject
string from left to right. Most characters stand for themselves in a
pattern, and match the corresponding characters in the subject. As a
trivial example, the pattern

The quick brown fox

matches a portion of a subject string that is identical to itself. The
power of regular expressions comes from the ability to include alterna-
tives and repetitions in the pattern. These are encoded in the pattern
by the use of meta-characters, which do not stand for themselves but
instead are interpreted in some special way.

There are two different sets of meta-characters: those that are recog-
nized anywhere in the pattern except within square brackets, and those
that are recognized in square brackets. Outside square brackets, the
meta-characters are as follows:

\ general escape character with several uses
^ assert start of string (or line, in multiline mode)
$ assert end of string (or line, in multiline mode)
. match any character except newline (by default)
[ start character class definition
| start of alternative branch
( start subpattern
) end subpattern
? extends the meaning of (
also 0 or 1 quantifier
also quantifier minimizer
* 0 or more quantifier
+ 1 or more quantifier
also "possessive quantifier"
{ start min/max quantifier

Part of a pattern that is in square brackets is called a "character
class". In a character class the only meta-characters are:

\ general escape character
^ negate the class, but only if the first character
- indicates character range
[ POSIX character class (only if followed by POSIX
syntax)
] terminates the character class

The following sections describe the use of each of the meta-characters.


BACKSLASH

The backslash character has several uses. Firstly, if it is followed by
a non-alphameric character, it takes away any special meaning that
character may have. This use of backslash as an escape character
applies both inside and outside character classes.

For example, if you want to match a * character, you write \* in the
pattern. This escaping action applies whether or not the following
character would otherwise be interpreted as a meta-character, so it is
always safe to precede a non-alphameric with backslash to specify that
it stands for itself. In particular, if you want to match a backslash,
you write \\.

If a pattern is compiled with the PCRE_EXTENDED option, whitespace in
the pattern (other than in a character class) and characters between a
# outside a character class and the next newline character are ignored.
An escaping backslash can be used to include a whitespace or # charac-
ter as part of the pattern.

If you want to remove the special meaning from a sequence of charac-
ters, you can do so by putting them between \Q and \E. This is differ-
ent from Perl in that $ and @ are handled as literals in \Q...\E
sequences in PCRE, whereas in Perl, $ and @ cause variable interpola-
tion. Note the following examples:

Pattern PCRE matches Perl matches

\Qabc$xyz\E abc$xyz abc followed by the
contents of $xyz
\Qabc\$xyz\E abc\$xyz abc\$xyz
\Qabc\E\$\Qxyz\E abc$xyz abc$xyz

The \Q...\E sequence is recognized both inside and outside character
classes.

A second use of backslash provides a way of encoding non-printing char-
acters in patterns in a visible manner. There is no restriction on the
appearance of non-printing characters, apart from the binary zero that
terminates a pattern, but when a pattern is being prepared by text
editing, it is usually easier to use one of the following escape
sequences than the binary character it represents:

\a alarm, that is, the BEL character (hex 07)
\cx "control-x", where x is any character
\e escape (hex 1B)
\f formfeed (hex 0C)
\n newline (hex 0A)
\r carriage return (hex 0D)
\t tab (hex 09)
\ddd character with octal code ddd, or backreference
\xhh character with hex code hh
\x{hhh..} character with hex code hhh... (UTF-8 mode only)

The precise effect of \cx is as follows: if x is a lower case letter,
it is converted to upper case. Then bit 6 of the character (hex 40) is
inverted. Thus \cz becomes hex 1A, but \c{ becomes hex 3B, while \c;
becomes hex 7B.

After \x, from zero to two hexadecimal digits are read (letters can be
in upper or lower case). In UTF-8 mode, any number of hexadecimal dig-
its may appear between \x{ and }, but the value of the character code
must be less than 2**31 (that is, the maximum hexadecimal value is
7FFFFFFF). If characters other than hexadecimal digits appear between
\x{ and }, or if there is no terminating }, this form of escape is not
recognized. Instead, the initial \x will be interpreted as a basic hex-
adecimal escape, with no following digits, giving a byte whose value is
zero.

Characters whose value is less than 256 can be defined by either of the
two syntaxes for \x when PCRE is in UTF-8 mode. There is no difference
in the way they are handled. For example, \xdc is exactly the same as
\x{dc}.

After \0 up to two further octal digits are read. In both cases, if
there are fewer than two digits, just those that are present are used.
Thus the sequence \0\x\07 specifies two binary zeros followed by a BEL
character (code value 7). Make sure you supply two digits after the
initial zero if the character that follows is itself an octal digit.

The handling of a backslash followed by a digit other than 0 is compli-
cated. Outside a character class, PCRE reads it and any following dig-
its as a decimal number. If the number is less than 10, or if there
have been at least that many previous capturing left parentheses in the
expression, the entire sequence is taken as a back reference. A
description of how this works is given later, following the discussion
of parenthesized subpatterns.

Inside a character class, or if the decimal number is greater than 9
and there have not been that many capturing subpatterns, PCRE re-reads
up to three octal digits following the backslash, and generates a sin-
gle byte from the least significant 8 bits of the value. Any subsequent
digits stand for themselves. For example:

\040 is another way of writing a space
\40 is the same, provided there are fewer than 40
previous capturing subpatterns
\7 is always a back reference
\11 might be a back reference, or another way of
writing a tab
\011 is always a tab
\0113 is a tab followed by the character "3"
\113 might be a back reference, otherwise the
character with octal code 113
\377 might be a back reference, otherwise
the byte consisting entirely of 1 bits
\81 is either a back reference, or a binary zero
followed by the two characters "8" and "1"

Note that octal values of 100 or greater must not be introduced by a
leading zero, because no more than three octal digits are ever read.

All the sequences that define a single byte value or a single UTF-8
character (in UTF-8 mode) can be used both inside and outside character
classes. In addition, inside a character class, the sequence \b is
interpreted as the backspace character (hex 08). Outside a character
class it has a different meaning (see below).

The third use of backslash is for specifying generic character types:

\d any decimal digit
\D any character that is not a decimal digit
\s any whitespace character
\S any character that is not a whitespace character
\w any "word" character
\W any "non-word" character

Each pair of escape sequences partitions the complete set of characters
into two disjoint sets. Any given character matches one, and only one,
of each pair.

In UTF-8 mode, characters with values greater than 255 never match \d,
\s, or \w, and always match \D, \S, and \W.

For compatibility with Perl, \s does not match the VT character (code
11). This makes it different from the the POSIX "space" class. The \s
characters are HT (9), LF (10), FF (12), CR (13), and space (32).

A "word" character is any letter or digit or the underscore character,
that is, any character which can be part of a Perl "word". The defini-
tion of letters and digits is controlled by PCRE's character tables,
and may vary if locale- specific matching is taking place (see "Locale
support" in the pcreapi page). For example, in the "fr" (French)
locale, some character codes greater than 128 are used for accented
letters, and these are matched by \w.

These character type sequences can appear both inside and outside char-
acter classes. They each match one character of the appropriate type.
If the current matching point is at the end of the subject string, all
of them fail, since there is no character to match.

The fourth use of backslash is for certain simple assertions. An asser-
tion specifies a condition that has to be met at a particular point in
a match, without consuming any characters from the subject string. The
use of subpatterns for more complicated assertions is described below.
The backslashed assertions are

\b matches at a word boundary
\B matches when not at a word boundary
\A matches at start of subject
\Z matches at end of subject or before newline at end
\z matches at end of subject
\G matches at first matching position in subject

These assertions may not appear in character classes (but note that \b
has a different meaning, namely the backspace character, inside a char-
acter class).

A word boundary is a position in the subject string where the current
character and the previous character do not both match \w or \W (i.e.
one matches \w and the other matches \W), or the start or end of the
string if the first or last character matches \w, respectively.

The \A, \Z, and \z assertions differ from the traditional circumflex
and dollar (described below) in that they only ever match at the very
start and end of the subject string, whatever options are set. Thus,
they are independent of multiline mode.

They are not affected by the PCRE_NOTBOL or PCRE_NOTEOL options. If the
startoffset argument of pcre_exec() is non-zero, indicating that match-
ing is to start at a point other than the beginning of the subject, \A
can never match. The difference between \Z and \z is that \Z matches
before a newline that is the last character of the string as well as at
the end of the string, whereas \z matches only at the end.

The \G assertion is true only when the current matching position is at
the start point of the match, as specified by the startoffset argument
of pcre_exec(). It differs from \A when the value of startoffset is
non-zero. By calling pcre_exec() multiple times with appropriate argu-
ments, you can mimic Perl's /g option, and it is in this kind of imple-
mentation where \G can be useful.

Note, however, that PCRE's interpretation of \G, as the start of the
current match, is subtly different from Perl's, which defines it as the
end of the previous match. In Perl, these can be different when the
previously matched string was empty. Because PCRE does just one match
at a time, it cannot reproduce this behaviour.

If all the alternatives of a pattern begin with \G, the expression is
anchored to the starting match position, and the "anchored" flag is set
in the compiled regular expression.


CIRCUMFLEX AND DOLLAR

Outside a character class, in the default matching mode, the circumflex
character is an assertion which is true only if the current matching
point is at the start of the subject string. If the startoffset argu-
ment of pcre_exec() is non-zero, circumflex can never match if the
PCRE_MULTILINE option is unset. Inside a character class, circumflex
has an entirely different meaning (see below).

Circumflex need not be the first character of the pattern if a number
of alternatives are involved, but it should be the first thing in each
alternative in which it appears if the pattern is ever to match that
branch. If all possible alternatives start with a circumflex, that is,
if the pattern is constrained to match only at the start of the sub-
ject, it is said to be an "anchored" pattern. (There are also other
constructs that can cause a pattern to be anchored.)

A dollar character is an assertion which is true only if the current
matching point is at the end of the subject string, or immediately
before a newline character that is the last character in the string (by
default). Dollar need not be the last character of the pattern if a
number of alternatives are involved, but it should be the last item in
any branch in which it appears. Dollar has no special meaning in a
character class.

The meaning of dollar can be changed so that it matches only at the
very end of the string, by setting the PCRE_DOLLAR_ENDONLY option at
compile time. This does not affect the \Z assertion.

The meanings of the circumflex and dollar characters are changed if the
PCRE_MULTILINE option is set. When this is the case, they match immedi-
ately after and immediately before an internal newline character,
respectively, in addition to matching at the start and end of the sub-
ject string. For example, the pattern /^abc$/ matches the subject
string "def\nabc" in multiline mode, but not otherwise. Consequently,
patterns that are anchored in single line mode because all branches
start with ^ are not anchored in multiline mode, and a match for cir-
cumflex is possible when the startoffset argument of pcre_exec() is
non-zero. The PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE
is set.

Note that the sequences \A, \Z, and \z can be used to match the start
and end of the subject in both modes, and if all branches of a pattern
start with \A it is always anchored, whether PCRE_MULTILINE is set or
not.


FULL STOP (PERIOD, DOT)

Outside a character class, a dot in the pattern matches any one charac-
ter in the subject, including a non-printing character, but not (by
default) newline. In UTF-8 mode, a dot matches any UTF-8 character,
which might be more than one byte long, except (by default) for new-
line. If the PCRE_DOTALL option is set, dots match newlines as well.
The handling of dot is entirely independent of the handling of circum-
flex and dollar, the only relationship being that they both involve
newline characters. Dot has no special meaning in a character class.


MATCHING A SINGLE BYTE

Outside a character class, the escape sequence \C matches any one byte,
both in and out of UTF-8 mode. Unlike a dot, it always matches a new-
line. The feature is provided in Perl in order to match individual
bytes in UTF-8 mode. Because it breaks up UTF-8 characters into indi-
vidual bytes, what remains in the string may be a malformed UTF-8
string. For this reason it is best avoided.

PCRE does not allow \C to appear in lookbehind assertions (see below),
because in UTF-8 mode it makes it impossible to calculate the length of
the lookbehind.


SQUARE BRACKETS

An opening square bracket introduces a character class, terminated by a
closing square bracket. A closing square bracket on its own is not spe-
cial. If a closing square bracket is required as a member of the class,
it should be the first data character in the class (after an initial
circumflex, if present) or escaped with a backslash.

A character class matches a single character in the subject. In UTF-8
mode, the character may occupy more than one byte. A matched character
must be in the set of characters defined by the class, unless the first
character in the class definition is a circumflex, in which case the
subject character must not be in the set defined by the class. If a
circumflex is actually required as a member of the class, ensure it is
not the first character, or escape it with a backslash.

For example, the character class [aeiou] matches any lower case vowel,
while [^aeiou] matches any character that is not a lower case vowel.
Note that a circumflex is just a convenient notation for specifying the
characters which are in the class by enumerating those that are not. It
is not an assertion: it still consumes a character from the subject
string, and fails if the current pointer is at the end of the string.

In UTF-8 mode, characters with values greater than 255 can be included
in a class as a literal string of bytes, or by using the \x{ escaping
mechanism.

When caseless matching is set, any letters in a class represent both
their upper case and lower case versions, so for example, a caseless
[aeiou] matches "A" as well as "a", and a caseless [^aeiou] does not
match "A", whereas a caseful version would. PCRE does not support the
concept of case for characters with values greater than 255.

The newline character is never treated in any special way in character
classes, whatever the setting of the PCRE_DOTALL or PCRE_MULTILINE
options is. A class such as [^a] will always match a newline.

The minus (hyphen) character can be used to specify a range of charac-
ters in a character class. For example, [d-m] matches any letter
between d and m, inclusive. If a minus character is required in a
class, it must be escaped with a backslash or appear in a position
where it cannot be interpreted as indicating a range, typically as the
first or last character in the class.

It is not possible to have the literal character "]" as the end charac-
ter of a range. A pattern such as [W-]46] is interpreted as a class of
two characters ("W" and "-") followed by a literal string "46]", so it
would match "W46]" or "-46]". However, if the "]" is escaped with a
backslash it is interpreted as the end of range, so [W-\]46] is inter-
preted as a single class containing a range followed by two separate
characters. The octal or hexadecimal representation of "]" can also be
used to end a range.

Ranges operate in the collating sequence of character values. They can
also be used for characters specified numerically, for example
[\000-\037]. In UTF-8 mode, ranges can include characters whose values
are greater than 255, for example [\x{100}-\x{2ff}].

If a range that includes letters is used when caseless matching is set,
it matches the letters in either case. For example, [W-c] is equivalent
to [][\^_`wxyzabc], matched caselessly, and if character tables for the
"fr" locale are in use, [\xc8-\xcb] matches accented E characters in
both cases.

The character types \d, \D, \s, \S, \w, and \W may also appear in a
character class, and add the characters that they match to the class.
For example, [\dABCDEF] matches any hexadecimal digit. A circumflex can
conveniently be used with the upper case character types to specify a
more restricted set of characters than the matching lower case type.
For example, the class [^\W_] matches any letter or digit, but not
underscore.

All non-alphameric characters other than \, -, ^ (at the start) and the
terminating ] are non-special in character classes, but it does no harm
if they are escaped.


POSIX CHARACTER CLASSES

Perl supports the POSIX notation for character classes, which uses
names enclosed by [: and :] within the enclosing square brackets. PCRE
also supports this notation. For example,

[01[:alpha:]%]

matches "0", "1", any alphabetic character, or "%". The supported class
names are

alnum letters and digits
alpha letters
ascii character codes 0 - 127
blank space or tab only
cntrl control characters
digit decimal digits (same as \d)
graph printing characters, excluding space
lower lower case letters
print printing characters, including space
punct printing characters, excluding letters and digits
space white space (not quite the same as \s)
upper upper case letters
word "word" characters (same as \w)
xdigit hexadecimal digits

The "space" characters are HT (9), LF (10), VT (11), FF (12), CR (13),
and space (32). Notice that this list includes the VT character (code
11). This makes "space" different to \s, which does not include VT (for
Perl compatibility).

The name "word" is a Perl extension, and "blank" is a GNU extension
from Perl 5.8. Another Perl extension is negation, which is indicated
by a ^ character after the colon. For example,

[12[:^digit:]]

matches "1", "2", or any non-digit. PCRE (and Perl) also recognize the
POSIX syntax [.ch.] and [=ch=] where "ch" is a "collating element", but
these are not supported, and an error is given if they are encountered.

In UTF-8 mode, characters with values greater than 255 do not match any
of the POSIX character classes.


VERTICAL BAR

Vertical bar characters are used to separate alternative patterns. For
example, the pattern

gilbert|sullivan

matches either "gilbert" or "sullivan". Any number of alternatives may
appear, and an empty alternative is permitted (matching the empty
string). The matching process tries each alternative in turn, from
left to right, and the first one that succeeds is used. If the alterna-
tives are within a subpattern (defined below), "succeeds" means match-
ing the rest of the main pattern as well as the alternative in the sub-
pattern.


Continued on Regular Expressions 2


Prev | Next | Users Guide | PhantomScript Reference | P1 Systems

Phantom for Windows v1.7 Users Guide - Copyright © 2006 P1 Systems Incorporated. All Rights Reserved.