blob: dd82ff425b4ecd1a3f8df67e12750441fb9acbc4 [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
4\bimodindex{regex}
5This 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
11need of regular expressions should use the new \code{re} module, which
12supports the more powerful and regular Perl-style regular expressions.
13Existing code should be converted. The standard library module
14\code{reconvert} helps in converting \code{regex} style regular
Guido van Rossumb1b8f231997-12-30 04:53:49 +000015expressions to \code{re} style regular expressions. (For more
16conversion help, see the URL
17\file{http://starship.skyport.net/crew/amk/regex/regex-to-re.html}.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000018
Guido van Rossum6240b0b1996-10-24 22:49:13 +000019By default the patterns are Emacs-style regular expressions
20(with one exception). There is
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000021a way to change the syntax to match that of several well-known
Guido van Rossumfe4254e1995-08-11 00:31:57 +000022\UNIX{} utilities. The exception is that Emacs' \samp{\e s}
23pattern is not supported, since the original implementation references
24the Emacs syntax tables.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000025
26This module is 8-bit clean: both patterns and strings may contain null
27bytes and characters whose high bit is set.
28
Guido van Rossum326c0bc1994-01-03 00:00:31 +000029\strong{Please note:} There is a little-known fact about Python string
30literals which means that you don't usually have to worry about
31doubling backslashes, even though they are used to escape special
32characters in string literals as well as in regular expressions. This
33is because Python doesn't remove backslashes from string literals if
34they are followed by an unrecognized escape character.
35\emph{However}, if you want to include a literal \dfn{backslash} in a
36regular expression represented as a string literal, you have to
Guido van Rossum1f8cee21997-03-14 04:10:13 +000037\emph{quadruple} it or enclose it in a singleton character class.
38E.g.\ to extract \LaTeX\ \samp{\e section\{{\rm
Guido van Rossum326c0bc1994-01-03 00:00:31 +000039\ldots}\}} headers from a document, you can use this pattern:
Guido van Rossumeb0f0661997-12-30 20:38:16 +000040\code{'[\e ]section\{\e (.*\e )\}'}. \emph{Another exception:}
Guido van Rossum1a535601996-06-26 19:43:22 +000041the escape sequece \samp{\e b} is significant in string literals
42(where it means the ASCII bell character) as well as in Emacs regular
43expressions (where it stands for a word boundary), so in order to
44search for a word boundary, you should use the pattern \code{'\e \e b'}.
45Similarly, a backslash followed by a digit 0-7 should be doubled to
46avoid interpretation as an octal escape.
47
48\subsection{Regular Expressions}
49
50A regular expression (or RE) specifies a set of strings that matches
51it; the functions in this module let you check if a particular string
Guido van Rossum6240b0b1996-10-24 22:49:13 +000052matches a given regular expression (or if a given regular expression
53matches a particular string, which comes down to the same thing).
Guido van Rossum1a535601996-06-26 19:43:22 +000054
55Regular expressions can be concatenated to form new regular
56expressions; if \emph{A} and \emph{B} are both regular expressions,
57then \emph{AB} is also an regular expression. If a string \emph{p}
58matches A and another string \emph{q} matches B, the string \emph{pq}
59will match AB. Thus, complex expressions can easily be constructed
60from simpler ones like the primitives described here. For details of
61the theory and implementation of regular expressions, consult almost
62any textbook about compiler construction.
63
64% XXX The reference could be made more specific, say to
65% "Compilers: Principles, Techniques and Tools", by Alfred V. Aho,
66% Ravi Sethi, and Jeffrey D. Ullman, or some FA text.
67
Guido van Rossum6240b0b1996-10-24 22:49:13 +000068A brief explanation of the format of regular expressions follows.
Guido van Rossum1a535601996-06-26 19:43:22 +000069
70Regular expressions can contain both special and ordinary characters.
71Ordinary characters, like '\code{A}', '\code{a}', or '\code{0}', are
72the simplest regular expressions; they simply match themselves. You
73can concatenate ordinary characters, so '\code{last}' matches the
Guido van Rossum6240b0b1996-10-24 22:49:13 +000074characters 'last'. (In the rest of this section, we'll write RE's in
75\code{this special font}, usually without quotes, and strings to be
76matched 'in single quotes'.)
Guido van Rossum1a535601996-06-26 19:43:22 +000077
78Special characters either stand for classes of ordinary characters, or
79affect how the regular expressions around them are interpreted.
80
81The special characters are:
82\begin{itemize}
Fred Drake4b3f0311996-12-13 22:04:31 +000083\item[\code{.}] (Dot.) Matches any character except a newline.
84\item[\code{\^}] (Caret.) Matches the start of the string.
85\item[\code{\$}] Matches the end of the string.
Guido van Rossum1a535601996-06-26 19:43:22 +000086\code{foo} matches both 'foo' and 'foobar', while the regular
Fred Drake4b3f0311996-12-13 22:04:31 +000087expression '\code{foo\$}' matches only 'foo'.
Guido van Rossum1a535601996-06-26 19:43:22 +000088\item[\code{*}] Causes the resulting RE to
89match 0 or more repetitions of the preceding RE. \code{ab*} will
90match 'a', 'ab', or 'a' followed by any number of 'b's.
91\item[\code{+}] Causes the
92resulting RE to match 1 or more repetitions of the preceding RE.
93\code{ab+} will match 'a' followed by any non-zero number of 'b's; it
94will not match just 'a'.
95\item[\code{?}] Causes the resulting RE to
96match 0 or 1 repetitions of the preceding RE. \code{ab?} will
97match either 'a' or 'ab'.
98
99\item[\code{\e}] Either escapes special characters (permitting you to match
100characters like '*?+\&\$'), or signals a special sequence; special
101sequences are discussed below. Remember that Python also uses the
102backslash as an escape sequence in string literals; if the escape
103sequence isn't recognized by Python's parser, the backslash and
104subsequent character are included in the resulting string. However,
105if Python would recognize the resulting sequence, the backslash should
106be repeated twice.
107
108\item[\code{[]}] Used to indicate a set of characters. Characters can
109be listed individually, or a range is indicated by giving two
110characters and separating them by a '-'. Special characters are
111not active inside sets. For example, \code{[akm\$]}
112will match any of the characters 'a', 'k', 'm', or '\$'; \code{[a-z]} will
113match any lowercase letter.
114
115If you want to include a \code{]} inside a
116set, it must be the first character of the set; to include a \code{-},
117place it as the first or last character.
118
119Characters \emph{not} within a range can be matched by including a
120\code{\^} as the first character of the set; \code{\^} elsewhere will
121simply match the '\code{\^}' character.
122\end{itemize}
123
124The special sequences consist of '\code{\e}' and a character
125from the list below. If the ordinary character is not on the list,
126then the resulting RE will match the second character. For example,
127\code{\e\$} matches the character '\$'. Ones where the backslash
Guido van Rossumeb0f0661997-12-30 20:38:16 +0000128should be doubled in string literals are indicated.
Guido van Rossum1a535601996-06-26 19:43:22 +0000129
130\begin{itemize}
131\item[\code{\e|}]\code{A\e|B}, where A and B can be arbitrary REs,
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000132creates a regular expression that will match either A or B. This can
133be used inside groups (see below) as well.
Guido van Rossum1a535601996-06-26 19:43:22 +0000134%
Fred Drake4b3f0311996-12-13 22:04:31 +0000135\item[\code{\e( \e)}] Indicates the start and end of a group; the
Guido van Rossum1a535601996-06-26 19:43:22 +0000136contents of a group can be matched later in the string with the
Fred Drake4b3f0311996-12-13 22:04:31 +0000137\code{\e [1-9]} special sequence, described next.
Guido van Rossum1a535601996-06-26 19:43:22 +0000138%
139{\fulllineitems\item[\code{\e \e 1, ... \e \e 7, \e 8, \e 9}]
Fred Drake4b3f0311996-12-13 22:04:31 +0000140Matches the contents of the group of the same
Guido van Rossum1a535601996-06-26 19:43:22 +0000141number. For example, \code{\e (.+\e ) \e \e 1} matches 'the the' or
142'55 55', but not 'the end' (note the space after the group). This
143special sequence can only be used to match one of the first 9 groups;
144groups with higher numbers can be matched using the \code{\e v}
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000145sequence. (\code{\e 8} and \code{\e 9} don't need a double backslash
Fred Drake4b3f0311996-12-13 22:04:31 +0000146because they are not octal digits.)}
Guido van Rossum1a535601996-06-26 19:43:22 +0000147%
Fred Drake4b3f0311996-12-13 22:04:31 +0000148\item[\code{\e \e b}] Matches the empty string, but only at the
Guido van Rossum1a535601996-06-26 19:43:22 +0000149beginning or end of a word. A word is defined as a sequence of
150alphanumeric characters, so the end of a word is indicated by
Fred Drake4b3f0311996-12-13 22:04:31 +0000151whitespace or a non-alphanumeric character.
Guido van Rossum1a535601996-06-26 19:43:22 +0000152%
Fred Drake4b3f0311996-12-13 22:04:31 +0000153\item[\code{\e B}] Matches the empty string, but when it is \emph{not} at the
154beginning or end of a word.
Guido van Rossum1a535601996-06-26 19:43:22 +0000155%
Fred Drake4b3f0311996-12-13 22:04:31 +0000156\item[\code{\e v}] Must be followed by a two digit decimal number, and
157matches the contents of the group of the same number. The group number must be between 1 and 99, inclusive.
Guido van Rossum1a535601996-06-26 19:43:22 +0000158%
159\item[\code{\e w}]Matches any alphanumeric character; this is
160equivalent to the set \code{[a-zA-Z0-9]}.
161%
Fred Drake4b3f0311996-12-13 22:04:31 +0000162\item[\code{\e W}] Matches any non-alphanumeric character; this is
163equivalent to the set \code{[\^a-zA-Z0-9]}.
164\item[\code{\e <}] Matches the empty string, but only at the beginning of a
Guido van Rossum1a535601996-06-26 19:43:22 +0000165word. A word is defined as a sequence of alphanumeric characters, so
166the end of a word is indicated by whitespace or a non-alphanumeric
Fred Drake4b3f0311996-12-13 22:04:31 +0000167character.
168\item[\code{\e >}] Matches the empty string, but only at the end of a
169word.
Guido van Rossum1a535601996-06-26 19:43:22 +0000170
Fred Drake4b3f0311996-12-13 22:04:31 +0000171\item[\code{\e \e \e \e}] Matches a literal backslash.
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000172
Guido van Rossum1a535601996-06-26 19:43:22 +0000173% In Emacs, the following two are start of buffer/end of buffer. In
174% Python they seem to be synonyms for ^$.
Fred Drake4b3f0311996-12-13 22:04:31 +0000175\item[\code{\e `}] Like \code{\^}, this only matches at the start of the
176string.
Guido van Rossum1a535601996-06-26 19:43:22 +0000177\item[\code{\e \e '}] Like \code{\$}, this only matches at the end of the
178string.
179% end of buffer
180\end{itemize}
181
182\subsection{Module Contents}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000183
184The module defines these functions, and an exception:
185
186\renewcommand{\indexsubitem}{(in module regex)}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000187
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000188\begin{funcdesc}{match}{pattern\, string}
189 Return how many characters at the beginning of \var{string} match
190 the regular expression \var{pattern}. Return \code{-1} if the
191 string does not match the pattern (this is different from a
192 zero-length match!).
193\end{funcdesc}
194
195\begin{funcdesc}{search}{pattern\, string}
196 Return the first position in \var{string} that matches the regular
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000197 expression \var{pattern}. Return \code{-1} if no position in the string
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000198 matches the pattern (this is different from a zero-length match
199 anywhere!).
200\end{funcdesc}
201
Guido van Rossum16d6e711994-08-08 12:30:22 +0000202\begin{funcdesc}{compile}{pattern\optional{\, translate}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000203 Compile a regular expression pattern into a regular expression
204 object, which can be used for matching using its \code{match} and
Guido van Rossum470be141995-03-17 16:07:09 +0000205 \code{search} methods, described below. The optional argument
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000206 \var{translate}, if present, must be a 256-character string
207 indicating how characters (both of the pattern and of the strings to
208 be matched) are translated before comparing them; the \code{i}-th
209 element of the string gives the translation for the character with
Guido van Rossum470be141995-03-17 16:07:09 +0000210 \ASCII{} code \code{i}. This can be used to implement
211 case-insensitive matching; see the \code{casefold} data item below.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000212
213 The sequence
214
215\bcode\begin{verbatim}
216prog = regex.compile(pat)
217result = prog.match(str)
218\end{verbatim}\ecode
Guido van Rossume47da0a1997-07-17 16:34:52 +0000219%
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000220is equivalent to
221
222\bcode\begin{verbatim}
223result = regex.match(pat, str)
224\end{verbatim}\ecode
Guido van Rossume47da0a1997-07-17 16:34:52 +0000225%
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000226but the version using \code{compile()} is more efficient when multiple
227regular expressions are used concurrently in a single program. (The
228compiled version of the last pattern passed to \code{regex.match()} or
229\code{regex.search()} is cached, so programs that use only a single
230regular expression at a time needn't worry about compiling regular
231expressions.)
232\end{funcdesc}
233
234\begin{funcdesc}{set_syntax}{flags}
235 Set the syntax to be used by future calls to \code{compile},
236 \code{match} and \code{search}. (Already compiled expression objects
237 are not affected.) The argument is an integer which is the OR of
238 several flag bits. The return value is the previous value of
239 the syntax flags. Names for the flags are defined in the standard
240 module \code{regex_syntax}; read the file \file{regex_syntax.py} for
241 more information.
242\end{funcdesc}
243
Barry Warsawcd77df61997-02-18 18:54:30 +0000244\begin{funcdesc}{get_syntax}{}
245 Returns the current value of the syntax flags as an integer.
246\end{funcdesc}
247
Guido van Rossum16d6e711994-08-08 12:30:22 +0000248\begin{funcdesc}{symcomp}{pattern\optional{\, translate}}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000249This is like \code{compile}, but supports symbolic group names: if a
Guido van Rossum6c4f0031995-03-07 10:14:09 +0000250parenthesis-enclosed group begins with a group name in angular
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000251brackets, e.g. \code{'\e(<id>[a-z][a-z0-9]*\e)'}, the group can
252be referenced by its name in arguments to the \code{group} method of
253the resulting compiled regular expression object, like this:
Guido van Rossum7defee71995-02-27 17:52:35 +0000254\code{p.group('id')}. Group names may contain alphanumeric characters
255and \code{'_'} only.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000256\end{funcdesc}
257
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000258\begin{excdesc}{error}
259 Exception raised when a string passed to one of the functions here
260 is not a valid regular expression (e.g., unmatched parentheses) or
261 when some other error occurs during compilation or matching. (It is
262 never an error if a string contains no match for a pattern.)
263\end{excdesc}
264
265\begin{datadesc}{casefold}
266A string suitable to pass as \var{translate} argument to
267\code{compile} to map all upper case characters to their lowercase
268equivalents.
269\end{datadesc}
270
271\noindent
272Compiled regular expression objects support these methods:
273
274\renewcommand{\indexsubitem}{(regex method)}
Guido van Rossum16d6e711994-08-08 12:30:22 +0000275\begin{funcdesc}{match}{string\optional{\, pos}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000276 Return how many characters at the beginning of \var{string} match
277 the compiled regular expression. Return \code{-1} if the string
278 does not match the pattern (this is different from a zero-length
279 match!).
280
281 The optional second parameter \var{pos} gives an index in the string
282 where the search is to start; it defaults to \code{0}. This is not
283 completely equivalent to slicing the string; the \code{'\^'} pattern
284 character matches at the real begin of the string and at positions
285 just after a newline, not necessarily at the index where the search
286 is to start.
287\end{funcdesc}
288
Guido van Rossum16d6e711994-08-08 12:30:22 +0000289\begin{funcdesc}{search}{string\optional{\, pos}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000290 Return the first position in \var{string} that matches the regular
291 expression \code{pattern}. Return \code{-1} if no position in the
292 string matches the pattern (this is different from a zero-length
293 match anywhere!).
294
295 The optional second parameter has the same meaning as for the
296 \code{match} method.
297\end{funcdesc}
298
299\begin{funcdesc}{group}{index\, index\, ...}
300This method is only valid when the last call to the \code{match}
301or \code{search} method found a match. It returns one or more
302groups of the match. If there is a single \var{index} argument,
303the result is a single string; if there are multiple arguments, the
304result is a tuple with one item per argument. If the \var{index} is
305zero, the corresponding return value is the entire matching string; if
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000306it is in the inclusive range [1..99], it is the string matching the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000307the corresponding parenthesized group (using the default syntax,
Fred Drake875c8071998-01-02 02:50:13 +0000308groups are parenthesized using \code{{\e}(} and \code{{\e})}). If no
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000309such group exists, the corresponding result is \code{None}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000310
311If the regular expression was compiled by \code{symcomp} instead of
312\code{compile}, the \var{index} arguments may also be strings
313identifying groups by their group name.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000314\end{funcdesc}
315
316\noindent
317Compiled regular expressions support these data attributes:
318
319\renewcommand{\indexsubitem}{(regex attribute)}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000320
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000321\begin{datadesc}{regs}
322When the last call to the \code{match} or \code{search} method found a
323match, this is a tuple of pairs of indices corresponding to the
324beginning and end of all parenthesized groups in the pattern. Indices
325are relative to the string argument passed to \code{match} or
326\code{search}. The 0-th tuple gives the beginning and end or the
327whole pattern. When the last match or search failed, this is
328\code{None}.
329\end{datadesc}
330
331\begin{datadesc}{last}
332When the last call to the \code{match} or \code{search} method found a
333match, this is the string argument passed to that method. When the
334last match or search failed, this is \code{None}.
335\end{datadesc}
336
337\begin{datadesc}{translate}
338This is the value of the \var{translate} argument to
339\code{regex.compile} that created this regular expression object. If
340the \var{translate} argument was omitted in the \code{regex.compile}
341call, this is \code{None}.
342\end{datadesc}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000343
344\begin{datadesc}{givenpat}
345The regular expression pattern as passed to \code{compile} or
346\code{symcomp}.
347\end{datadesc}
348
349\begin{datadesc}{realpat}
350The regular expression after stripping the group names for regular
351expressions compiled with \code{symcomp}. Same as \code{givenpat}
352otherwise.
353\end{datadesc}
354
355\begin{datadesc}{groupindex}
356A dictionary giving the mapping from symbolic group names to numerical
357group indices for regular expressions compiled with \code{symcomp}.
358\code{None} otherwise.
359\end{datadesc}