blob: f3a3fa9254eb567986231410e312845d047f49ac [file] [log] [blame]
Guido van Rossum5fdeeea1994-01-02 01:22:07 +00001\section{Built-in Module \sectcode{regex}}
Guido van Rossume47da0a1997-07-17 16:34:52 +00002\label{module-regex}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +00003\bimodindex{regex}
Fred Drake054f8fd1998-01-12 18:28:20 +00004
Guido van Rossum5fdeeea1994-01-02 01:22:07 +00005This module provides regular expression matching operations similar to
Guido van Rossum28f9a681997-12-09 19:45:47 +00006those found in Emacs.
7
8\strong{Obsolescence note:}
9This module is obsolete as of Python version 1.5; it is still being
10maintained because much existing code still uses it. All new code in
Fred Drake054f8fd1998-01-12 18:28:20 +000011need of regular expressions should use the new
12\code{re}\refstmodindex{re} module, which supports the more powerful
13and regular Perl-style regular expressions. Existing code should be
14converted. The standard library module
15\code{reconvert}\refstmodindex{reconvert} helps in converting
16\code{regex} style regular expressions to \code{re}\refstmodindex{re}
17style regular expressions. (For more conversion help, see the URL
Fred Drake16f88451998-01-22 20:47:26 +000018\url{http://starship.skyport.net/crew/amk/regex/regex-to-re.html}.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000019
Guido van Rossum6240b0b1996-10-24 22:49:13 +000020By default the patterns are Emacs-style regular expressions
21(with one exception). There is
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000022a way to change the syntax to match that of several well-known
Guido van Rossumfe4254e1995-08-11 00:31:57 +000023\UNIX{} utilities. The exception is that Emacs' \samp{\e s}
24pattern is not supported, since the original implementation references
25the Emacs syntax tables.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000026
27This module is 8-bit clean: both patterns and strings may contain null
28bytes and characters whose high bit is set.
29
Guido van Rossum326c0bc1994-01-03 00:00:31 +000030\strong{Please note:} There is a little-known fact about Python string
31literals which means that you don't usually have to worry about
32doubling backslashes, even though they are used to escape special
33characters in string literals as well as in regular expressions. This
34is because Python doesn't remove backslashes from string literals if
35they are followed by an unrecognized escape character.
36\emph{However}, if you want to include a literal \dfn{backslash} in a
37regular expression represented as a string literal, you have to
Guido van Rossum1f8cee21997-03-14 04:10:13 +000038\emph{quadruple} it or enclose it in a singleton character class.
39E.g.\ to extract \LaTeX\ \samp{\e section\{{\rm
Guido van Rossum326c0bc1994-01-03 00:00:31 +000040\ldots}\}} headers from a document, you can use this pattern:
Guido van Rossumeb0f0661997-12-30 20:38:16 +000041\code{'[\e ]section\{\e (.*\e )\}'}. \emph{Another exception:}
Guido van Rossum1a535601996-06-26 19:43:22 +000042the escape sequece \samp{\e b} is significant in string literals
43(where it means the ASCII bell character) as well as in Emacs regular
44expressions (where it stands for a word boundary), so in order to
45search for a word boundary, you should use the pattern \code{'\e \e b'}.
46Similarly, a backslash followed by a digit 0-7 should be doubled to
47avoid interpretation as an octal escape.
48
49\subsection{Regular Expressions}
50
51A regular expression (or RE) specifies a set of strings that matches
52it; the functions in this module let you check if a particular string
Guido van Rossum6240b0b1996-10-24 22:49:13 +000053matches a given regular expression (or if a given regular expression
54matches a particular string, which comes down to the same thing).
Guido van Rossum1a535601996-06-26 19:43:22 +000055
56Regular expressions can be concatenated to form new regular
57expressions; if \emph{A} and \emph{B} are both regular expressions,
58then \emph{AB} is also an regular expression. If a string \emph{p}
59matches A and another string \emph{q} matches B, the string \emph{pq}
60will match AB. Thus, complex expressions can easily be constructed
61from simpler ones like the primitives described here. For details of
62the theory and implementation of regular expressions, consult almost
63any textbook about compiler construction.
64
65% XXX The reference could be made more specific, say to
66% "Compilers: Principles, Techniques and Tools", by Alfred V. Aho,
67% Ravi Sethi, and Jeffrey D. Ullman, or some FA text.
68
Guido van Rossum6240b0b1996-10-24 22:49:13 +000069A brief explanation of the format of regular expressions follows.
Guido van Rossum1a535601996-06-26 19:43:22 +000070
71Regular expressions can contain both special and ordinary characters.
72Ordinary characters, like '\code{A}', '\code{a}', or '\code{0}', are
73the simplest regular expressions; they simply match themselves. You
74can concatenate ordinary characters, so '\code{last}' matches the
Guido van Rossum6240b0b1996-10-24 22:49:13 +000075characters 'last'. (In the rest of this section, we'll write RE's in
76\code{this special font}, usually without quotes, and strings to be
77matched 'in single quotes'.)
Guido van Rossum1a535601996-06-26 19:43:22 +000078
79Special characters either stand for classes of ordinary characters, or
80affect how the regular expressions around them are interpreted.
81
82The special characters are:
83\begin{itemize}
Fred Drake4b3f0311996-12-13 22:04:31 +000084\item[\code{.}] (Dot.) Matches any character except a newline.
85\item[\code{\^}] (Caret.) Matches the start of the string.
86\item[\code{\$}] Matches the end of the string.
Guido van Rossum1a535601996-06-26 19:43:22 +000087\code{foo} matches both 'foo' and 'foobar', while the regular
Fred Drake4b3f0311996-12-13 22:04:31 +000088expression '\code{foo\$}' matches only 'foo'.
Guido van Rossum1a535601996-06-26 19:43:22 +000089\item[\code{*}] Causes the resulting RE to
90match 0 or more repetitions of the preceding RE. \code{ab*} will
91match 'a', 'ab', or 'a' followed by any number of 'b's.
92\item[\code{+}] Causes the
93resulting RE to match 1 or more repetitions of the preceding RE.
94\code{ab+} will match 'a' followed by any non-zero number of 'b's; it
95will not match just 'a'.
96\item[\code{?}] Causes the resulting RE to
97match 0 or 1 repetitions of the preceding RE. \code{ab?} will
98match either 'a' or 'ab'.
99
100\item[\code{\e}] Either escapes special characters (permitting you to match
101characters like '*?+\&\$'), or signals a special sequence; special
102sequences are discussed below. Remember that Python also uses the
103backslash as an escape sequence in string literals; if the escape
104sequence isn't recognized by Python's parser, the backslash and
105subsequent character are included in the resulting string. However,
106if Python would recognize the resulting sequence, the backslash should
107be repeated twice.
108
109\item[\code{[]}] Used to indicate a set of characters. Characters can
110be listed individually, or a range is indicated by giving two
111characters and separating them by a '-'. Special characters are
112not active inside sets. For example, \code{[akm\$]}
113will match any of the characters 'a', 'k', 'm', or '\$'; \code{[a-z]} will
114match any lowercase letter.
115
116If you want to include a \code{]} inside a
117set, it must be the first character of the set; to include a \code{-},
118place it as the first or last character.
119
120Characters \emph{not} within a range can be matched by including a
121\code{\^} as the first character of the set; \code{\^} elsewhere will
122simply match the '\code{\^}' character.
123\end{itemize}
124
125The special sequences consist of '\code{\e}' and a character
126from the list below. If the ordinary character is not on the list,
127then the resulting RE will match the second character. For example,
128\code{\e\$} matches the character '\$'. Ones where the backslash
Guido van Rossumeb0f0661997-12-30 20:38:16 +0000129should be doubled in string literals are indicated.
Guido van Rossum1a535601996-06-26 19:43:22 +0000130
131\begin{itemize}
132\item[\code{\e|}]\code{A\e|B}, where A and B can be arbitrary REs,
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000133creates a regular expression that will match either A or B. This can
134be used inside groups (see below) as well.
Guido van Rossum1a535601996-06-26 19:43:22 +0000135%
Fred Drake4b3f0311996-12-13 22:04:31 +0000136\item[\code{\e( \e)}] Indicates the start and end of a group; the
Guido van Rossum1a535601996-06-26 19:43:22 +0000137contents of a group can be matched later in the string with the
Fred Drake4b3f0311996-12-13 22:04:31 +0000138\code{\e [1-9]} special sequence, described next.
Guido van Rossum1a535601996-06-26 19:43:22 +0000139%
140{\fulllineitems\item[\code{\e \e 1, ... \e \e 7, \e 8, \e 9}]
Fred Drake4b3f0311996-12-13 22:04:31 +0000141Matches the contents of the group of the same
Guido van Rossum1a535601996-06-26 19:43:22 +0000142number. For example, \code{\e (.+\e ) \e \e 1} matches 'the the' or
143'55 55', but not 'the end' (note the space after the group). This
144special sequence can only be used to match one of the first 9 groups;
145groups with higher numbers can be matched using the \code{\e v}
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000146sequence. (\code{\e 8} and \code{\e 9} don't need a double backslash
Fred Drake4b3f0311996-12-13 22:04:31 +0000147because they are not octal digits.)}
Guido van Rossum1a535601996-06-26 19:43:22 +0000148%
Fred Drake4b3f0311996-12-13 22:04:31 +0000149\item[\code{\e \e b}] Matches the empty string, but only at the
Guido van Rossum1a535601996-06-26 19:43:22 +0000150beginning or end of a word. A word is defined as a sequence of
151alphanumeric characters, so the end of a word is indicated by
Fred Drake4b3f0311996-12-13 22:04:31 +0000152whitespace or a non-alphanumeric character.
Guido van Rossum1a535601996-06-26 19:43:22 +0000153%
Fred Drake4b3f0311996-12-13 22:04:31 +0000154\item[\code{\e B}] Matches the empty string, but when it is \emph{not} at the
155beginning or end of a word.
Guido van Rossum1a535601996-06-26 19:43:22 +0000156%
Fred Drake4b3f0311996-12-13 22:04:31 +0000157\item[\code{\e v}] Must be followed by a two digit decimal number, and
Fred Drake054f8fd1998-01-12 18:28:20 +0000158matches the contents of the group of the same number. The group
159number must be between 1 and 99, inclusive.
Guido van Rossum1a535601996-06-26 19:43:22 +0000160%
161\item[\code{\e w}]Matches any alphanumeric character; this is
162equivalent to the set \code{[a-zA-Z0-9]}.
163%
Fred Drake4b3f0311996-12-13 22:04:31 +0000164\item[\code{\e W}] Matches any non-alphanumeric character; this is
165equivalent to the set \code{[\^a-zA-Z0-9]}.
166\item[\code{\e <}] Matches the empty string, but only at the beginning of a
Guido van Rossum1a535601996-06-26 19:43:22 +0000167word. A word is defined as a sequence of alphanumeric characters, so
168the end of a word is indicated by whitespace or a non-alphanumeric
Fred Drake4b3f0311996-12-13 22:04:31 +0000169character.
170\item[\code{\e >}] Matches the empty string, but only at the end of a
171word.
Guido van Rossum1a535601996-06-26 19:43:22 +0000172
Fred Drake4b3f0311996-12-13 22:04:31 +0000173\item[\code{\e \e \e \e}] Matches a literal backslash.
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000174
Guido van Rossum1a535601996-06-26 19:43:22 +0000175% In Emacs, the following two are start of buffer/end of buffer. In
176% Python they seem to be synonyms for ^$.
Fred Drake4b3f0311996-12-13 22:04:31 +0000177\item[\code{\e `}] Like \code{\^}, this only matches at the start of the
178string.
Fred Drake054f8fd1998-01-12 18:28:20 +0000179\item[\code{\e \e '}] Like \code{\$}, this only matches at the end of
180the string.
Guido van Rossum1a535601996-06-26 19:43:22 +0000181% end of buffer
182\end{itemize}
183
184\subsection{Module Contents}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000185
186The module defines these functions, and an exception:
187
188\renewcommand{\indexsubitem}{(in module regex)}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000189
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000190\begin{funcdesc}{match}{pattern\, string}
191 Return how many characters at the beginning of \var{string} match
192 the regular expression \var{pattern}. Return \code{-1} if the
193 string does not match the pattern (this is different from a
194 zero-length match!).
195\end{funcdesc}
196
197\begin{funcdesc}{search}{pattern\, string}
198 Return the first position in \var{string} that matches the regular
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000199 expression \var{pattern}. Return \code{-1} if no position in the string
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000200 matches the pattern (this is different from a zero-length match
201 anywhere!).
202\end{funcdesc}
203
Guido van Rossum16d6e711994-08-08 12:30:22 +0000204\begin{funcdesc}{compile}{pattern\optional{\, translate}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000205 Compile a regular expression pattern into a regular expression
Fred Drake054f8fd1998-01-12 18:28:20 +0000206 object, which can be used for matching using its \code{match()} and
207 \code{search()} methods, described below. The optional argument
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000208 \var{translate}, if present, must be a 256-character string
209 indicating how characters (both of the pattern and of the strings to
Fred Drake054f8fd1998-01-12 18:28:20 +0000210 be matched) are translated before comparing them; the \var{i}-th
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000211 element of the string gives the translation for the character with
Fred Drake054f8fd1998-01-12 18:28:20 +0000212 \ASCII{} code \var{i}. This can be used to implement
Guido van Rossum470be141995-03-17 16:07:09 +0000213 case-insensitive matching; see the \code{casefold} data item below.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000214
215 The sequence
216
217\bcode\begin{verbatim}
218prog = regex.compile(pat)
219result = prog.match(str)
220\end{verbatim}\ecode
Guido van Rossume47da0a1997-07-17 16:34:52 +0000221%
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000222is equivalent to
223
224\bcode\begin{verbatim}
225result = regex.match(pat, str)
226\end{verbatim}\ecode
Fred Drake054f8fd1998-01-12 18:28:20 +0000227
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000228but the version using \code{compile()} is more efficient when multiple
229regular expressions are used concurrently in a single program. (The
230compiled version of the last pattern passed to \code{regex.match()} or
231\code{regex.search()} is cached, so programs that use only a single
232regular expression at a time needn't worry about compiling regular
233expressions.)
234\end{funcdesc}
235
236\begin{funcdesc}{set_syntax}{flags}
Fred Drake054f8fd1998-01-12 18:28:20 +0000237 Set the syntax to be used by future calls to \code{compile()},
238 \code{match()} and \code{search()}. (Already compiled expression
239 objects are not affected.) The argument is an integer which is the
240 OR of several flag bits. The return value is the previous value of
241 the syntax flags. Names for the flags are defined in the standard
242 module \code{regex_syntax}\refstmodindex{regex_syntax}; read the
243 file \file{regex_syntax.py} for more information.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000244\end{funcdesc}
245
Barry Warsawcd77df61997-02-18 18:54:30 +0000246\begin{funcdesc}{get_syntax}{}
247 Returns the current value of the syntax flags as an integer.
248\end{funcdesc}
249
Guido van Rossum16d6e711994-08-08 12:30:22 +0000250\begin{funcdesc}{symcomp}{pattern\optional{\, translate}}
Fred Drake054f8fd1998-01-12 18:28:20 +0000251This is like \code{compile()}, but supports symbolic group names: if a
Guido van Rossum6c4f0031995-03-07 10:14:09 +0000252parenthesis-enclosed group begins with a group name in angular
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000253brackets, e.g. \code{'\e(<id>[a-z][a-z0-9]*\e)'}, the group can
Fred Drake054f8fd1998-01-12 18:28:20 +0000254be referenced by its name in arguments to the \code{group()} method of
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000255the resulting compiled regular expression object, like this:
Guido van Rossum7defee71995-02-27 17:52:35 +0000256\code{p.group('id')}. Group names may contain alphanumeric characters
257and \code{'_'} only.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000258\end{funcdesc}
259
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000260\begin{excdesc}{error}
261 Exception raised when a string passed to one of the functions here
262 is not a valid regular expression (e.g., unmatched parentheses) or
263 when some other error occurs during compilation or matching. (It is
264 never an error if a string contains no match for a pattern.)
265\end{excdesc}
266
267\begin{datadesc}{casefold}
Fred Drake054f8fd1998-01-12 18:28:20 +0000268A string suitable to pass as the \var{translate} argument to
269\code{compile()} to map all upper case characters to their lowercase
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000270equivalents.
271\end{datadesc}
272
273\noindent
274Compiled regular expression objects support these methods:
275
276\renewcommand{\indexsubitem}{(regex method)}
Guido van Rossum16d6e711994-08-08 12:30:22 +0000277\begin{funcdesc}{match}{string\optional{\, pos}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000278 Return how many characters at the beginning of \var{string} match
279 the compiled regular expression. Return \code{-1} if the string
280 does not match the pattern (this is different from a zero-length
281 match!).
282
Fred Drake054f8fd1998-01-12 18:28:20 +0000283 The optional second parameter, \var{pos}, gives an index in the string
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000284 where the search is to start; it defaults to \code{0}. This is not
285 completely equivalent to slicing the string; the \code{'\^'} pattern
286 character matches at the real begin of the string and at positions
287 just after a newline, not necessarily at the index where the search
288 is to start.
289\end{funcdesc}
290
Guido van Rossum16d6e711994-08-08 12:30:22 +0000291\begin{funcdesc}{search}{string\optional{\, pos}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000292 Return the first position in \var{string} that matches the regular
293 expression \code{pattern}. Return \code{-1} if no position in the
294 string matches the pattern (this is different from a zero-length
295 match anywhere!).
296
297 The optional second parameter has the same meaning as for the
Fred Drake054f8fd1998-01-12 18:28:20 +0000298 \code{match()} method.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000299\end{funcdesc}
300
301\begin{funcdesc}{group}{index\, index\, ...}
Fred Drake054f8fd1998-01-12 18:28:20 +0000302This method is only valid when the last call to the \code{match()}
303or \code{search()} method found a match. It returns one or more
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000304groups of the match. If there is a single \var{index} argument,
305the result is a single string; if there are multiple arguments, the
306result is a tuple with one item per argument. If the \var{index} is
307zero, the corresponding return value is the entire matching string; if
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000308it is in the inclusive range [1..99], it is the string matching the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000309the corresponding parenthesized group (using the default syntax,
Fred Drake875c8071998-01-02 02:50:13 +0000310groups are parenthesized using \code{{\e}(} and \code{{\e})}). If no
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000311such group exists, the corresponding result is \code{None}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000312
Fred Drake054f8fd1998-01-12 18:28:20 +0000313If the regular expression was compiled by \code{symcomp()} instead of
314\code{compile()}, the \var{index} arguments may also be strings
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000315identifying groups by their group name.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000316\end{funcdesc}
317
318\noindent
319Compiled regular expressions support these data attributes:
320
321\renewcommand{\indexsubitem}{(regex attribute)}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000322
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000323\begin{datadesc}{regs}
Fred Drake054f8fd1998-01-12 18:28:20 +0000324When the last call to the \code{match()} or \code{search()} method found a
325match, this is a tuple of pairs of indexes corresponding to the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000326beginning and end of all parenthesized groups in the pattern. Indices
Fred Drake054f8fd1998-01-12 18:28:20 +0000327are relative to the string argument passed to \code{match()} or
328\code{search()}. The 0-th tuple gives the beginning and end or the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000329whole pattern. When the last match or search failed, this is
330\code{None}.
331\end{datadesc}
332
333\begin{datadesc}{last}
Fred Drake054f8fd1998-01-12 18:28:20 +0000334When the last call to the \code{match()} or \code{search()} method found a
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000335match, this is the string argument passed to that method. When the
336last match or search failed, this is \code{None}.
337\end{datadesc}
338
339\begin{datadesc}{translate}
340This is the value of the \var{translate} argument to
Fred Drake054f8fd1998-01-12 18:28:20 +0000341\code{regex.compile()} that created this regular expression object. If
342the \var{translate} argument was omitted in the \code{regex.compile()}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000343call, this is \code{None}.
344\end{datadesc}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000345
346\begin{datadesc}{givenpat}
Fred Drake054f8fd1998-01-12 18:28:20 +0000347The regular expression pattern as passed to \code{compile()} or
348\code{symcomp()}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000349\end{datadesc}
350
351\begin{datadesc}{realpat}
352The regular expression after stripping the group names for regular
Fred Drake054f8fd1998-01-12 18:28:20 +0000353expressions compiled with \code{symcomp()}. Same as \code{givenpat}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000354otherwise.
355\end{datadesc}
356
357\begin{datadesc}{groupindex}
358A dictionary giving the mapping from symbolic group names to numerical
Fred Drake054f8fd1998-01-12 18:28:20 +0000359group indexes for regular expressions compiled with \code{symcomp()}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000360\code{None} otherwise.
361\end{datadesc}