A regular expression (or RE) specifies a set of strings that matches it; the functions in this module let you check if a particular string matches a given regular expression (or if a given regular expression matches a particular string, which comes down to the same thing).
Regular expressions can be concatenated to form new regular expressions; if A and B are both regular expressions, then AB is also an regular expression. If a string p matches A and another string q matches B, the string pq will match AB. Thus, complex expressions can easily be constructed from simpler ones like the primitives described here. For details of the theory and implementation of regular expressions, consult almost any textbook about compiler construction.
A brief explanation of the format of regular expressions follows.
Regular expressions can contain both special and ordinary characters.
Ordinary characters, like '
a', or '
the simplest regular expressions; they simply match themselves. You
can concatenate ordinary characters, so '
last' matches the
characters 'last'. (In the rest of this section, we'll write RE's in
this special font, usually without quotes, and strings to be
matched 'in single quotes'.)
Special characters either stand for classes of ordinary characters, or affect how the regular expressions around them are interpreted.
The special characters are:
foomatches both 'foo' and 'foobar', while the regular expression '
foo$' matches only 'foo'.
ab*will match 'a', 'ab', or 'a' followed by any number of 'b's.
ab+will match 'a' followed by any non-zero number of 'b's; it will not match just 'a'.
ab?will match either 'a' or 'ab'.
[akm$]will match any of the characters 'a', 'k', 'm', or '$';
[a-z]will match any lowercase letter.
If you want to include a
] inside a
set, it must be the first character of the set; to include a
place it as the first or last character.
Characters not within a range can be matched by including a
^ as the first character of the set;
^ elsewhere will
simply match the '
The special sequences consist of '
\' and a character
from the list below. If the ordinary character is not on the list,
then the resulting RE will match the second character. For example,
\$ matches the character '$'. Ones where the backslash
should be doubled in string literals are indicated.
A\|B, where A and B can be arbitrary REs, creates a regular expression that will match either A or B. This can be used inside groups (see below) as well.
\[1-9]special sequence, described next.
\\1, ... \\7, \8, \9
\(.+\) \\1matches 'the the' or '55 55', but not 'the end' (note the space after the group). This special sequence can only be used to match one of the first 9 groups; groups with higher numbers can be matched using the
\9don't need a double backslash because they are not octal digits.)
^, this only matches at the start of the string.
$, this only matches at the end of the string.