blob: 6582c72479a574e7f45f2b45a1d2607eaeb97404 [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 Drake859c7971998-03-06 15:11:30 +000018\url{http://starship.skyport.net/crew/amk/howto/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.
Fred Drake75bfb0f1998-02-19 06:32:06 +0000139\end{itemize}
140
141\begin{fulllineitems}
142\item[\code{\e \e 1, ... \e \e 7, \e 8, \e 9}]
Fred Drake4b3f0311996-12-13 22:04:31 +0000143Matches the contents of the group of the same
Guido van Rossum1a535601996-06-26 19:43:22 +0000144number. For example, \code{\e (.+\e ) \e \e 1} matches 'the the' or
145'55 55', but not 'the end' (note the space after the group). This
146special sequence can only be used to match one of the first 9 groups;
147groups with higher numbers can be matched using the \code{\e v}
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000148sequence. (\code{\e 8} and \code{\e 9} don't need a double backslash
Guido van Rossum38e0df31998-02-11 22:55:55 +0000149because they are not octal digits.)
Fred Drake75bfb0f1998-02-19 06:32:06 +0000150\end{fulllineitems}
151
152\begin{itemize}
Fred Drake4b3f0311996-12-13 22:04:31 +0000153\item[\code{\e \e b}] Matches the empty string, but only at the
Guido van Rossum1a535601996-06-26 19:43:22 +0000154beginning or end of a word. A word is defined as a sequence of
155alphanumeric characters, so the end of a word is indicated by
Fred Drake4b3f0311996-12-13 22:04:31 +0000156whitespace or a non-alphanumeric character.
Guido van Rossum1a535601996-06-26 19:43:22 +0000157%
Fred Drake4b3f0311996-12-13 22:04:31 +0000158\item[\code{\e B}] Matches the empty string, but when it is \emph{not} at the
159beginning or end of a word.
Guido van Rossum1a535601996-06-26 19:43:22 +0000160%
Fred Drake4b3f0311996-12-13 22:04:31 +0000161\item[\code{\e v}] Must be followed by a two digit decimal number, and
Fred Drake054f8fd1998-01-12 18:28:20 +0000162matches the contents of the group of the same number. The group
163number must be between 1 and 99, inclusive.
Guido van Rossum1a535601996-06-26 19:43:22 +0000164%
165\item[\code{\e w}]Matches any alphanumeric character; this is
166equivalent to the set \code{[a-zA-Z0-9]}.
167%
Fred Drake4b3f0311996-12-13 22:04:31 +0000168\item[\code{\e W}] Matches any non-alphanumeric character; this is
169equivalent to the set \code{[\^a-zA-Z0-9]}.
170\item[\code{\e <}] Matches the empty string, but only at the beginning of a
Guido van Rossum1a535601996-06-26 19:43:22 +0000171word. A word is defined as a sequence of alphanumeric characters, so
172the end of a word is indicated by whitespace or a non-alphanumeric
Fred Drake4b3f0311996-12-13 22:04:31 +0000173character.
174\item[\code{\e >}] Matches the empty string, but only at the end of a
175word.
Guido van Rossum1a535601996-06-26 19:43:22 +0000176
Fred Drake4b3f0311996-12-13 22:04:31 +0000177\item[\code{\e \e \e \e}] Matches a literal backslash.
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000178
Guido van Rossum1a535601996-06-26 19:43:22 +0000179% In Emacs, the following two are start of buffer/end of buffer. In
180% Python they seem to be synonyms for ^$.
Fred Drake4b3f0311996-12-13 22:04:31 +0000181\item[\code{\e `}] Like \code{\^}, this only matches at the start of the
182string.
Fred Drake054f8fd1998-01-12 18:28:20 +0000183\item[\code{\e \e '}] Like \code{\$}, this only matches at the end of
184the string.
Guido van Rossum1a535601996-06-26 19:43:22 +0000185% end of buffer
186\end{itemize}
187
188\subsection{Module Contents}
Guido van Rossum38e0df31998-02-11 22:55:55 +0000189\nodename{Contents of Module regex}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000190
191The module defines these functions, and an exception:
192
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000193
Fred Drakecce10901998-03-17 06:33:25 +0000194\begin{funcdesc}{match}{pattern, string}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000195 Return how many characters at the beginning of \var{string} match
196 the regular expression \var{pattern}. Return \code{-1} if the
197 string does not match the pattern (this is different from a
198 zero-length match!).
199\end{funcdesc}
200
Fred Drakecce10901998-03-17 06:33:25 +0000201\begin{funcdesc}{search}{pattern, string}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000202 Return the first position in \var{string} that matches the regular
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000203 expression \var{pattern}. Return \code{-1} if no position in the string
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000204 matches the pattern (this is different from a zero-length match
205 anywhere!).
206\end{funcdesc}
207
Fred Drakecce10901998-03-17 06:33:25 +0000208\begin{funcdesc}{compile}{pattern\optional{, translate}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000209 Compile a regular expression pattern into a regular expression
Fred Drake054f8fd1998-01-12 18:28:20 +0000210 object, which can be used for matching using its \code{match()} and
211 \code{search()} methods, described below. The optional argument
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000212 \var{translate}, if present, must be a 256-character string
213 indicating how characters (both of the pattern and of the strings to
Fred Drake054f8fd1998-01-12 18:28:20 +0000214 be matched) are translated before comparing them; the \var{i}-th
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000215 element of the string gives the translation for the character with
Fred Drake054f8fd1998-01-12 18:28:20 +0000216 \ASCII{} code \var{i}. This can be used to implement
Guido van Rossum470be141995-03-17 16:07:09 +0000217 case-insensitive matching; see the \code{casefold} data item below.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000218
219 The sequence
220
Fred Drake19479911998-02-13 06:58:54 +0000221\begin{verbatim}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000222prog = regex.compile(pat)
223result = prog.match(str)
Fred Drake19479911998-02-13 06:58:54 +0000224\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000225%
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000226is equivalent to
227
Fred Drake19479911998-02-13 06:58:54 +0000228\begin{verbatim}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000229result = regex.match(pat, str)
Fred Drake19479911998-02-13 06:58:54 +0000230\end{verbatim}
Fred Drake054f8fd1998-01-12 18:28:20 +0000231
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000232but the version using \code{compile()} is more efficient when multiple
233regular expressions are used concurrently in a single program. (The
234compiled version of the last pattern passed to \code{regex.match()} or
235\code{regex.search()} is cached, so programs that use only a single
236regular expression at a time needn't worry about compiling regular
237expressions.)
238\end{funcdesc}
239
240\begin{funcdesc}{set_syntax}{flags}
Fred Drake054f8fd1998-01-12 18:28:20 +0000241 Set the syntax to be used by future calls to \code{compile()},
242 \code{match()} and \code{search()}. (Already compiled expression
243 objects are not affected.) The argument is an integer which is the
244 OR of several flag bits. The return value is the previous value of
245 the syntax flags. Names for the flags are defined in the standard
246 module \code{regex_syntax}\refstmodindex{regex_syntax}; read the
247 file \file{regex_syntax.py} for more information.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000248\end{funcdesc}
249
Barry Warsawcd77df61997-02-18 18:54:30 +0000250\begin{funcdesc}{get_syntax}{}
251 Returns the current value of the syntax flags as an integer.
252\end{funcdesc}
253
Fred Drakecce10901998-03-17 06:33:25 +0000254\begin{funcdesc}{symcomp}{pattern\optional{, translate}}
Fred Drake054f8fd1998-01-12 18:28:20 +0000255This is like \code{compile()}, but supports symbolic group names: if a
Guido van Rossum6c4f0031995-03-07 10:14:09 +0000256parenthesis-enclosed group begins with a group name in angular
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000257brackets, e.g. \code{'\e(<id>[a-z][a-z0-9]*\e)'}, the group can
Fred Drake054f8fd1998-01-12 18:28:20 +0000258be referenced by its name in arguments to the \code{group()} method of
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000259the resulting compiled regular expression object, like this:
Guido van Rossum7defee71995-02-27 17:52:35 +0000260\code{p.group('id')}. Group names may contain alphanumeric characters
261and \code{'_'} only.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000262\end{funcdesc}
263
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000264\begin{excdesc}{error}
265 Exception raised when a string passed to one of the functions here
266 is not a valid regular expression (e.g., unmatched parentheses) or
267 when some other error occurs during compilation or matching. (It is
268 never an error if a string contains no match for a pattern.)
269\end{excdesc}
270
271\begin{datadesc}{casefold}
Fred Drake054f8fd1998-01-12 18:28:20 +0000272A string suitable to pass as the \var{translate} argument to
273\code{compile()} to map all upper case characters to their lowercase
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000274equivalents.
275\end{datadesc}
276
277\noindent
278Compiled regular expression objects support these methods:
279
Fred Drake19479911998-02-13 06:58:54 +0000280\setindexsubitem{(regex method)}
Fred Drakecce10901998-03-17 06:33:25 +0000281\begin{funcdesc}{match}{string\optional{, pos}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000282 Return how many characters at the beginning of \var{string} match
283 the compiled regular expression. Return \code{-1} if the string
284 does not match the pattern (this is different from a zero-length
285 match!).
286
Fred Drake054f8fd1998-01-12 18:28:20 +0000287 The optional second parameter, \var{pos}, gives an index in the string
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000288 where the search is to start; it defaults to \code{0}. This is not
289 completely equivalent to slicing the string; the \code{'\^'} pattern
290 character matches at the real begin of the string and at positions
291 just after a newline, not necessarily at the index where the search
292 is to start.
293\end{funcdesc}
294
Fred Drakecce10901998-03-17 06:33:25 +0000295\begin{funcdesc}{search}{string\optional{, pos}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000296 Return the first position in \var{string} that matches the regular
297 expression \code{pattern}. Return \code{-1} if no position in the
298 string matches the pattern (this is different from a zero-length
299 match anywhere!).
300
301 The optional second parameter has the same meaning as for the
Fred Drake054f8fd1998-01-12 18:28:20 +0000302 \code{match()} method.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000303\end{funcdesc}
304
Fred Drakecce10901998-03-17 06:33:25 +0000305\begin{funcdesc}{group}{index, index, ...}
Fred Drake054f8fd1998-01-12 18:28:20 +0000306This method is only valid when the last call to the \code{match()}
307or \code{search()} method found a match. It returns one or more
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000308groups of the match. If there is a single \var{index} argument,
309the result is a single string; if there are multiple arguments, the
310result is a tuple with one item per argument. If the \var{index} is
311zero, the corresponding return value is the entire matching string; if
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000312it is in the inclusive range [1..99], it is the string matching the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000313the corresponding parenthesized group (using the default syntax,
Fred Drake875c8071998-01-02 02:50:13 +0000314groups are parenthesized using \code{{\e}(} and \code{{\e})}). If no
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000315such group exists, the corresponding result is \code{None}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000316
Fred Drake054f8fd1998-01-12 18:28:20 +0000317If the regular expression was compiled by \code{symcomp()} instead of
318\code{compile()}, the \var{index} arguments may also be strings
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000319identifying groups by their group name.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000320\end{funcdesc}
321
322\noindent
323Compiled regular expressions support these data attributes:
324
Fred Drake19479911998-02-13 06:58:54 +0000325\setindexsubitem{(regex attribute)}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000326
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000327\begin{datadesc}{regs}
Fred Drake054f8fd1998-01-12 18:28:20 +0000328When the last call to the \code{match()} or \code{search()} method found a
329match, this is a tuple of pairs of indexes corresponding to the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000330beginning and end of all parenthesized groups in the pattern. Indices
Fred Drake054f8fd1998-01-12 18:28:20 +0000331are relative to the string argument passed to \code{match()} or
332\code{search()}. The 0-th tuple gives the beginning and end or the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000333whole pattern. When the last match or search failed, this is
334\code{None}.
335\end{datadesc}
336
337\begin{datadesc}{last}
Fred Drake054f8fd1998-01-12 18:28:20 +0000338When the last call to the \code{match()} or \code{search()} method found a
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000339match, this is the string argument passed to that method. When the
340last match or search failed, this is \code{None}.
341\end{datadesc}
342
343\begin{datadesc}{translate}
344This is the value of the \var{translate} argument to
Fred Drake054f8fd1998-01-12 18:28:20 +0000345\code{regex.compile()} that created this regular expression object. If
346the \var{translate} argument was omitted in the \code{regex.compile()}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000347call, this is \code{None}.
348\end{datadesc}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000349
350\begin{datadesc}{givenpat}
Fred Drake054f8fd1998-01-12 18:28:20 +0000351The regular expression pattern as passed to \code{compile()} or
352\code{symcomp()}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000353\end{datadesc}
354
355\begin{datadesc}{realpat}
356The regular expression after stripping the group names for regular
Fred Drake054f8fd1998-01-12 18:28:20 +0000357expressions compiled with \code{symcomp()}. Same as \code{givenpat}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000358otherwise.
359\end{datadesc}
360
361\begin{datadesc}{groupindex}
362A dictionary giving the mapping from symbolic group names to numerical
Fred Drake054f8fd1998-01-12 18:28:20 +0000363group indexes for regular expressions compiled with \code{symcomp()}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000364\code{None} otherwise.
365\end{datadesc}