Node: Regular Expressions, Next: , Previous: Keywords, Up: Standard Procedures



Regular Expressions

STKLOS uses the Philip Hazel's Perl-compatible Regular Expression (PCRE) library for implementing regexps [PCRE01]. Consequently, the STKLOS regular expression syntax is the same as PCRE, and Perl by the way.

The following text is extracted from the PCRE package. However, to make things shorter, some of the original documentation as not been reported here. In particular some possibilities of PCRE have been completely occulted (those whose description was too long and which seems (at least to me), not too important). Read the documentation provided with PCRE for a complete description1.

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 alternatives 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 recognized 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 subject (or line, in multiline mode)
$ assert end of subject (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
{ 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
] 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 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 "\" to specify that it stands for itself. In particular, if you want to match a backslash, you write "\\".

Another 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.

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a "word".

These character type sequences can appear both inside and outside character 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.

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. Inside a character class, circumflex has an entirely different meaning (see below).

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 has no special meaning in a character class.

The meanings of the circumflex and dollar characters are changed if the MULTILINE option is set. When this is the case, they match immediately after and immediately before an internal "\n" character, respectively, in addition to matching at the start and end of the subject string. For example, the pattern ^abc$ matches the subject string "def\nabc" in multiline mode, but not otherwise.

Dot

Outside a character class, a dot in the pattern matches any one character in the subject, including a non-printing character, but not (by default) newline. If the DOTALL option is set, dots match newlines as well. The handling of dot is entirely independent of the handling of circumflex and dollar, the only relationship being that they both involve newline characters. Dot has no special meaning in a character class.

Square Braquets

An opening square bracket introduces a character class, terminated by a closing square bracket. A closing square bracket on its own is not special. 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; the character must be in the set of characters defined by the class, unless the first character in the class 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.

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.

The newline character is never treated in any special way in character classes, whatever the setting of the DOTALL or 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 characters 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.

Ranges operate in ASCII collating sequence. They can also be used for characters specified numerically. 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.

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.

POSIX Character Classes

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

       [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
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 (same as \s)
upper upper case letters
word "word" characters (same as \w)
xdigit hexadecimal digits

If an option change occurs inside a subpattern, the effect is different. This is a change of behaviour in Perl 5.005. An option change inside a subpattern affects only that part of the subpattern that follows it, so

       (a(?i)b)c
     

matches abc and aBc and no other strings (assuming CASELESS is not used).

Subpatterns

Subpatterns are delimited by parentheses (round brackets), which can be nested. Marking part of a pattern as a subpattern does two things:

  1. It localizes a set of alternatives. For example, the pattern
                cat(aract|erpillar|)
              
    matches one of the words "cat", "cataract", or "caterpillar". Without the parentheses, it would match "cataract", "erpillar" or the empty string.
  2. It sets up the subpattern as a capturing subpattern (as defined above). Opening parentheses are counted from left to right (starting from 1) to obtain the numbers of the capturing subpatterns.

    For example, if the string "the red king" is matched against the pattern

                the ((red|white) (king|queen))
              

    the captured substrings are "red king", "red", and "king", and are numbered 1, 2, and 3.

Repetition

Repetition is specified by quantifiers, which can follow any of the following items:

The general repetition quantifier specifies a minimum and maximum number of permitted matches, by giving the two numbers in curly brackets (braces), separated by a comma. The numbers must be less than 65536, and the first must be less than or equal to the second. For example:

       z{2,4}
     

matches "zz", "zzz", or "zzzz". A closing brace on its own is not a special character. If the second number is omitted, but the comma is present, there is no upper limit; if the second number and the comma are both omitted, the quantifier specifies an exact number of required matches. Thus

       [aeiou]{3,}
     

matches at least 3 successive vowels, but may match many more, while

       \d{8}
     

matches exactly 8 digits. An opening curly bracket that appears in a position where a quantifier is not allowed, or one that does not match the syntax of a quantifier, is taken as a literal character. For example, {,6} is not a quantifier, but a literal string of four characters.

The quantifier {0} is permitted, causing the expression to behave as if the previous item and the quantifier were not present.

For convenience (and historical compatibility) the three most common quantifiers have single-character abbreviations:

* is equivalent to {0,}
+ is equivalent to {1,}
? is equivalent to {0,1}

It is possible to construct infinite loops by following a subpattern that can match no characters with a quantifier that has no upper limit, for example:

       (a?)*
     

By default, the quantifiers are "greedy", that is, they match as much as possible (up to the maximum number of permitted times), without causing the rest of the pattern to fail. The classic example of where this gives problems is in trying to match comments in C programs. These appear between the sequences /* and */ and within the sequence, individual * and / characters may appear. An attempt to match C comments by applying the pattern

       /\*.*\*/
     

to the string

       /* first command */  not comment  /* second comment */
     

fails, because it matches the entire string owing to the greediness of the .* item.

However, if a quantifier is followed by a question mark, it ceases to be greedy, and instead matches the minimum number of times possible, so the pattern

       /\*.*?\*/
     

does the right thing with the C comments. The meaning of the various quantifiers is not otherwise changed, just the preferred number of matches. Do not confuse this use of question mark with its use as a quantifier in its own right. Because it has two uses, it can sometimes appear doubled, as in

       \d??\d
     

which matches one digit by preference, but can match two if that is the only way the rest of the pattern matches.

Back References

Outside a character class, a backslash followed by a digit is a back reference to a capturing subpattern earlier (i.e. to its left) in the pattern, provided there have been that many previous capturing left parentheses.

A back reference matches whatever actually matched the capturing subpattern in the current subject string, rather than anything matching the subpattern itself. So the pattern

       (sens|respons)e and \1ibility
     

matches "sense and sensibility" and "response and responsibility", but not "sense and responsibility". If caseful matching is in force at the time of the back reference, the case of letters is relevant. For example,

       ((?i)rah)\s+\1
     

matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original capturing subpattern is matched caselessly.

Assertions

An assertion is a test on the characters following or preceding the current matching point that does not actually consume any characters. The simple assertions coded as ^ and $ are described above. More complicated assertions are coded as subpatterns. There are two kinds: those that look ahead of the current position in the subject string, and those that look behind it.

An assertion subpattern is matched in the normal way, except that it does not cause the current matching position to be changed. Lookahead assertions start with (?= for positive assertions and (?! for negative assertions. For example,

       \w+(?=;)
     

matches a word followed by a semicolon, but does not include the semicolon in the match, and

       foo(?!bar)
     

matches any occurrence of "foo" that is not followed by "bar". Note that the apparently similar pattern

       (?!foo)bar
     

does not find an occurrence of "bar" that is preceded by something other than "foo"; it finds any occurrence of "bar" whatsoever, because the assertion (?!foo) is always true when the next three characters are "bar". A lookbehind assertion is needed to achieve this effect.

Lookbehind assertions start with (?<= for positive assertions and (?<! for negative assertions. For example,

       (?<!foo)bar
     

does find an occurrence of "bar" that is not preceded by "foo". The contents of a lookbehind assertion are restricted such that all the strings it matches must have a fixed length. However, if there are several alternatives, they do not all have to have the same fixed length. Thus

       (?<=bullock|donkey)
     

is permitted, but

       (?<!dogs?|cats?)
     

causes an error at compile time. Branches that match different length strings are permitted only at the top level of a lookbehind assertion. This is an extension compared with Perl 5.005, which requires all branches to match the same length of string. An assertion such as

       (?<=ab(c|de))
     

is not permitted, because its single top-level branch can match two different lengths, but it is acceptable if rewritten to use two top-level branches:

       (?<=abc|abde)
     

The implementation of lookbehind assertions is, for each alternative, to temporarily move the current position back by the fixed width and then try to match. If there are insufficient characters before the current position, the match is deemed to fail. Lookbehinds in conjunction with once-only subpatterns can be particularly useful for matching at the ends of strings; an example is given at the end of the section on once-only subpatterns.

Several assertions (of any sort) may occur in succession. For example,

       (?<=\d{3})(?<!999)foo
     

matches "foo" preceded by three digits that are not "999". Notice that each of the assertions is applied independently at the same point in the subject string. First there is a check that the previous three characters are all digits, and then there is a check that the same three characters are not "999". This pattern does not match "foo" preceded by six characters, the first of which are digits and the last three of which are not "999". For example, it doesn't match "123abcfoo". A pattern to do that is

       (?<=\d{3}...)(?<!999)foo
     

This time the first assertion looks at the preceding six characters, checking that the first three are digits, and then the second assertion checks that the preceding three characters are not "999".

Assertions count towards the maximum of 200 parenthesized subpatterns.

Other features

As said before, only a subset of PCRE is described in this document. In particulars points such as

will not be discussed here. See the PCRE documentation for more details.

string->regexp string STKLOS Procedure
String->regexp takes a string representation of a regular expression and compiles it into a regexp value. Other regular expression procedures accept either a string or a regexp value as the matching pattern. If a regular expression string is used multiple times, it is faster to compile the string once to a regexp value and use it for repeated matches instead of using the string each time.

regexp? obj STKLOS Procedure
Regexp returns #t if obj is a regexp value created by the regexp, otherwise regexp returns #f.

regexp-match pattern str STKLOS Procedure
regexp-match-positions pattern str STKLOS Procedure
These functions attempt to match pattern (a string or a regexp value) to str. If the match fails, #f is returned. If the match succeeds, a list (containing strings for regexp-match and positions for regexp-match-positions is returned. The first string (or positions) in this list is the portion of string that matched pattern. If two portions of string can match pattern, then the earliest and longest match is found, by default.

Additional strings or positions are returned in the list if pattern contains parenthesized sub-expressions; matches for the sub-expressions are provided in the order of the opening parentheses in pattern.

          (regexp-match-positions "ca" "abracadabra")
                           => ((4 6))
          (regexp-match-positions "CA" "abracadabra")
                           => #f
          (regexp-match-positions "(?i)CA" "abracadabra")
                           => ((4 6))
          (regexp-match "(a*)(b*)(c*)" "abc")
                           => ("abc" "a" "b" "c")
          (regexp-match-positions "(a*)(b*)(c*)" "abc")
                           => ((0 3) (0 1) (1 2) (2 3))
          (regexp-match-positions "(a*)(b*)(c*)" "c")
                           => ((0 1) (0 0) (0 0) (0 1))
          (regexp-match "(?<=\\d{3})(?<!999)foo" "999foo and 123foo")
               => ((14 17))
          

regexp-replace pattern string substitution STKLOS Procedure
regexp-replace-all pattern string substitution STKLOS Procedure
Regexp-replace matches the regular expression pattern against string. If there is a match, the portion of string which matches pattern is replaced by the substitution string. If there is no match, regexp-replace returns string unmodified. Note that the given pattern could be here either a string or a regular expression.

If pattern contains \n where n is a digit between 1 and 9, then it is replaced in the substitution with the portion of string that matched the n-th parenthesized subexpression of pattern. If n is equal to 0, then it is replaced in substitution with the portion of string that matched pattern.

Regexp-replace replaces the first occurrence of pattern in string. To replace all the occurrences of pattern, use regexp-replace-all.

          (regexp-replace "a*b" "aaabbcccc" "X")
                             => "Xbcccc"
          (regexp-replace (string->regexp "a*b") "aaabbcccc" "X")
                             => "Xbcccc"
          (regexp-replace "(a*)b" "aaabbcccc" "X\\1Y")
                             => "XaaaYbcccc"
          (regexp-replace "f(.*)r" "foobar" "\\1 \\1")
                             => "ooba ooba"
          (regexp-replace "f(.*)r" "foobar" "\\0 \\0")
                             => "foobar foobar"
          
          (regexp-replace "a*b" "aaabbcccc" "X")
                             => "Xbcccc"
          (regexp-replace-all "a*b" "aaabbcccc" "X")
                             => "XXcccc"
          

regexp-quote str STKLOS Procedure
Takes an arbitrary string and returns a string where characters of str that could serve as regexp metacharacters are escaped with a backslash, so that they safely match only themselves.
          (regexp-quote "cons")       => "cons"
          (regexp-quote "list?")      => "list\\?"
          
regexp-quote is useful when building a composite regexp from a mix of regexp strings and verbatim strings.


Footnotes

  1. The latest release of PCRE is available from <ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre>