blob: 444b9229f512ddd056b9a7b0883192df02967db7 [file] [log] [blame]
Fred Drake295da241998-08-10 19:42:37 +00001\section{\module{regex} ---
2 Regular expression search and match operations.}
Fred Drakeb91e9341998-07-23 17:59:49 +00003\declaremodule{builtin}{regex}
4
5\modulesynopsis{Regular expression search and match operations.}
6
Fred Drake054f8fd1998-01-12 18:28:20 +00007
Guido van Rossum5fdeeea1994-01-02 01:22:07 +00008This module provides regular expression matching operations similar to
Guido van Rossum28f9a681997-12-09 19:45:47 +00009those found in Emacs.
10
11\strong{Obsolescence note:}
12This module is obsolete as of Python version 1.5; it is still being
13maintained because much existing code still uses it. All new code in
Fred Drake054f8fd1998-01-12 18:28:20 +000014need of regular expressions should use the new
15\code{re}\refstmodindex{re} module, which supports the more powerful
16and regular Perl-style regular expressions. Existing code should be
17converted. The standard library module
18\code{reconvert}\refstmodindex{reconvert} helps in converting
19\code{regex} style regular expressions to \code{re}\refstmodindex{re}
Fred Drake9da38811998-04-09 14:06:33 +000020style regular expressions. (For more conversion help, see Andrew
21Kuchling's\index{Kuchling, Andrew} ``\module{regex-to-re} HOWTO'' at
22\url{http://www.python.org/doc/howto/regex-to-re/}.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000023
Guido van Rossum6240b0b1996-10-24 22:49:13 +000024By default the patterns are Emacs-style regular expressions
25(with one exception). There is
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000026a way to change the syntax to match that of several well-known
Guido van Rossumfe4254e1995-08-11 00:31:57 +000027\UNIX{} utilities. The exception is that Emacs' \samp{\e s}
28pattern is not supported, since the original implementation references
29the Emacs syntax tables.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000030
31This module is 8-bit clean: both patterns and strings may contain null
32bytes and characters whose high bit is set.
33
Guido van Rossum326c0bc1994-01-03 00:00:31 +000034\strong{Please note:} There is a little-known fact about Python string
35literals which means that you don't usually have to worry about
36doubling backslashes, even though they are used to escape special
37characters in string literals as well as in regular expressions. This
38is because Python doesn't remove backslashes from string literals if
39they are followed by an unrecognized escape character.
40\emph{However}, if you want to include a literal \dfn{backslash} in a
41regular expression represented as a string literal, you have to
Guido van Rossum1f8cee21997-03-14 04:10:13 +000042\emph{quadruple} it or enclose it in a singleton character class.
Fred Drakefee6abe1998-12-10 19:57:52 +000043E.g.\ to extract \LaTeX\ \samp{\e section\{\textrm{\ldots}\}} headers
44from a document, you can use this pattern:
Guido van Rossumeb0f0661997-12-30 20:38:16 +000045\code{'[\e ]section\{\e (.*\e )\}'}. \emph{Another exception:}
Guido van Rossum1a535601996-06-26 19:43:22 +000046the escape sequece \samp{\e b} is significant in string literals
47(where it means the ASCII bell character) as well as in Emacs regular
48expressions (where it stands for a word boundary), so in order to
49search for a word boundary, you should use the pattern \code{'\e \e b'}.
50Similarly, a backslash followed by a digit 0-7 should be doubled to
51avoid interpretation as an octal escape.
52
53\subsection{Regular Expressions}
54
55A regular expression (or RE) specifies a set of strings that matches
56it; the functions in this module let you check if a particular string
Guido van Rossum6240b0b1996-10-24 22:49:13 +000057matches a given regular expression (or if a given regular expression
58matches a particular string, which comes down to the same thing).
Guido van Rossum1a535601996-06-26 19:43:22 +000059
60Regular expressions can be concatenated to form new regular
61expressions; if \emph{A} and \emph{B} are both regular expressions,
62then \emph{AB} is also an regular expression. If a string \emph{p}
63matches A and another string \emph{q} matches B, the string \emph{pq}
64will match AB. Thus, complex expressions can easily be constructed
65from simpler ones like the primitives described here. For details of
66the theory and implementation of regular expressions, consult almost
67any textbook about compiler construction.
68
69% XXX The reference could be made more specific, say to
70% "Compilers: Principles, Techniques and Tools", by Alfred V. Aho,
71% Ravi Sethi, and Jeffrey D. Ullman, or some FA text.
72
Guido van Rossum6240b0b1996-10-24 22:49:13 +000073A brief explanation of the format of regular expressions follows.
Guido van Rossum1a535601996-06-26 19:43:22 +000074
75Regular expressions can contain both special and ordinary characters.
76Ordinary characters, like '\code{A}', '\code{a}', or '\code{0}', are
77the simplest regular expressions; they simply match themselves. You
78can concatenate ordinary characters, so '\code{last}' matches the
Guido van Rossum6240b0b1996-10-24 22:49:13 +000079characters 'last'. (In the rest of this section, we'll write RE's in
80\code{this special font}, usually without quotes, and strings to be
81matched 'in single quotes'.)
Guido van Rossum1a535601996-06-26 19:43:22 +000082
83Special characters either stand for classes of ordinary characters, or
84affect how the regular expressions around them are interpreted.
85
86The special characters are:
87\begin{itemize}
Fred Drake4b3f0311996-12-13 22:04:31 +000088\item[\code{.}] (Dot.) Matches any character except a newline.
89\item[\code{\^}] (Caret.) Matches the start of the string.
90\item[\code{\$}] Matches the end of the string.
Guido van Rossum1a535601996-06-26 19:43:22 +000091\code{foo} matches both 'foo' and 'foobar', while the regular
Fred Drake4b3f0311996-12-13 22:04:31 +000092expression '\code{foo\$}' matches only 'foo'.
Guido van Rossum1a535601996-06-26 19:43:22 +000093\item[\code{*}] Causes the resulting RE to
94match 0 or more repetitions of the preceding RE. \code{ab*} will
95match 'a', 'ab', or 'a' followed by any number of 'b's.
96\item[\code{+}] Causes the
97resulting RE to match 1 or more repetitions of the preceding RE.
98\code{ab+} will match 'a' followed by any non-zero number of 'b's; it
99will not match just 'a'.
100\item[\code{?}] Causes the resulting RE to
101match 0 or 1 repetitions of the preceding RE. \code{ab?} will
102match either 'a' or 'ab'.
103
104\item[\code{\e}] Either escapes special characters (permitting you to match
105characters like '*?+\&\$'), or signals a special sequence; special
106sequences are discussed below. Remember that Python also uses the
107backslash as an escape sequence in string literals; if the escape
108sequence isn't recognized by Python's parser, the backslash and
109subsequent character are included in the resulting string. However,
110if Python would recognize the resulting sequence, the backslash should
111be repeated twice.
112
113\item[\code{[]}] Used to indicate a set of characters. Characters can
114be listed individually, or a range is indicated by giving two
115characters and separating them by a '-'. Special characters are
116not active inside sets. For example, \code{[akm\$]}
117will match any of the characters 'a', 'k', 'm', or '\$'; \code{[a-z]} will
118match any lowercase letter.
119
120If you want to include a \code{]} inside a
121set, it must be the first character of the set; to include a \code{-},
122place it as the first or last character.
123
124Characters \emph{not} within a range can be matched by including a
125\code{\^} as the first character of the set; \code{\^} elsewhere will
126simply match the '\code{\^}' character.
127\end{itemize}
128
129The special sequences consist of '\code{\e}' and a character
130from the list below. If the ordinary character is not on the list,
131then the resulting RE will match the second character. For example,
132\code{\e\$} matches the character '\$'. Ones where the backslash
Guido van Rossumeb0f0661997-12-30 20:38:16 +0000133should be doubled in string literals are indicated.
Guido van Rossum1a535601996-06-26 19:43:22 +0000134
135\begin{itemize}
136\item[\code{\e|}]\code{A\e|B}, where A and B can be arbitrary REs,
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000137creates a regular expression that will match either A or B. This can
138be used inside groups (see below) as well.
Guido van Rossum1a535601996-06-26 19:43:22 +0000139%
Fred Drake4b3f0311996-12-13 22:04:31 +0000140\item[\code{\e( \e)}] Indicates the start and end of a group; the
Guido van Rossum1a535601996-06-26 19:43:22 +0000141contents of a group can be matched later in the string with the
Fred Drake4b3f0311996-12-13 22:04:31 +0000142\code{\e [1-9]} special sequence, described next.
Fred Drake75bfb0f1998-02-19 06:32:06 +0000143\end{itemize}
144
145\begin{fulllineitems}
146\item[\code{\e \e 1, ... \e \e 7, \e 8, \e 9}]
Fred Drake4b3f0311996-12-13 22:04:31 +0000147Matches the contents of the group of the same
Guido van Rossum1a535601996-06-26 19:43:22 +0000148number. For example, \code{\e (.+\e ) \e \e 1} matches 'the the' or
149'55 55', but not 'the end' (note the space after the group). This
150special sequence can only be used to match one of the first 9 groups;
151groups with higher numbers can be matched using the \code{\e v}
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000152sequence. (\code{\e 8} and \code{\e 9} don't need a double backslash
Guido van Rossum38e0df31998-02-11 22:55:55 +0000153because they are not octal digits.)
Fred Drake75bfb0f1998-02-19 06:32:06 +0000154\end{fulllineitems}
155
156\begin{itemize}
Fred Drake4b3f0311996-12-13 22:04:31 +0000157\item[\code{\e \e b}] Matches the empty string, but only at the
Guido van Rossum1a535601996-06-26 19:43:22 +0000158beginning or end of a word. A word is defined as a sequence of
159alphanumeric characters, so the end of a word is indicated by
Fred Drake4b3f0311996-12-13 22:04:31 +0000160whitespace or a non-alphanumeric character.
Guido van Rossum1a535601996-06-26 19:43:22 +0000161%
Fred Drake4b3f0311996-12-13 22:04:31 +0000162\item[\code{\e B}] Matches the empty string, but when it is \emph{not} at the
163beginning or end of a word.
Guido van Rossum1a535601996-06-26 19:43:22 +0000164%
Fred Drake4b3f0311996-12-13 22:04:31 +0000165\item[\code{\e v}] Must be followed by a two digit decimal number, and
Fred Drake054f8fd1998-01-12 18:28:20 +0000166matches the contents of the group of the same number. The group
167number must be between 1 and 99, inclusive.
Guido van Rossum1a535601996-06-26 19:43:22 +0000168%
169\item[\code{\e w}]Matches any alphanumeric character; this is
170equivalent to the set \code{[a-zA-Z0-9]}.
171%
Fred Drake4b3f0311996-12-13 22:04:31 +0000172\item[\code{\e W}] Matches any non-alphanumeric character; this is
173equivalent to the set \code{[\^a-zA-Z0-9]}.
174\item[\code{\e <}] Matches the empty string, but only at the beginning of a
Guido van Rossum1a535601996-06-26 19:43:22 +0000175word. A word is defined as a sequence of alphanumeric characters, so
176the end of a word is indicated by whitespace or a non-alphanumeric
Fred Drake4b3f0311996-12-13 22:04:31 +0000177character.
178\item[\code{\e >}] Matches the empty string, but only at the end of a
179word.
Guido van Rossum1a535601996-06-26 19:43:22 +0000180
Fred Drake4b3f0311996-12-13 22:04:31 +0000181\item[\code{\e \e \e \e}] Matches a literal backslash.
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000182
Guido van Rossum1a535601996-06-26 19:43:22 +0000183% In Emacs, the following two are start of buffer/end of buffer. In
184% Python they seem to be synonyms for ^$.
Fred Drake4b3f0311996-12-13 22:04:31 +0000185\item[\code{\e `}] Like \code{\^}, this only matches at the start of the
186string.
Fred Drake054f8fd1998-01-12 18:28:20 +0000187\item[\code{\e \e '}] Like \code{\$}, this only matches at the end of
188the string.
Guido van Rossum1a535601996-06-26 19:43:22 +0000189% end of buffer
190\end{itemize}
191
192\subsection{Module Contents}
Guido van Rossum38e0df31998-02-11 22:55:55 +0000193\nodename{Contents of Module regex}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000194
195The module defines these functions, and an exception:
196
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000197
Fred Drakecce10901998-03-17 06:33:25 +0000198\begin{funcdesc}{match}{pattern, string}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000199 Return how many characters at the beginning of \var{string} match
200 the regular expression \var{pattern}. Return \code{-1} if the
201 string does not match the pattern (this is different from a
202 zero-length match!).
203\end{funcdesc}
204
Fred Drakecce10901998-03-17 06:33:25 +0000205\begin{funcdesc}{search}{pattern, string}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000206 Return the first position in \var{string} that matches the regular
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000207 expression \var{pattern}. Return \code{-1} if no position in the string
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000208 matches the pattern (this is different from a zero-length match
209 anywhere!).
210\end{funcdesc}
211
Fred Drakecce10901998-03-17 06:33:25 +0000212\begin{funcdesc}{compile}{pattern\optional{, translate}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000213 Compile a regular expression pattern into a regular expression
Fred Drake054f8fd1998-01-12 18:28:20 +0000214 object, which can be used for matching using its \code{match()} and
215 \code{search()} methods, described below. The optional argument
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000216 \var{translate}, if present, must be a 256-character string
217 indicating how characters (both of the pattern and of the strings to
Fred Drake054f8fd1998-01-12 18:28:20 +0000218 be matched) are translated before comparing them; the \var{i}-th
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000219 element of the string gives the translation for the character with
Fred Drake054f8fd1998-01-12 18:28:20 +0000220 \ASCII{} code \var{i}. This can be used to implement
Guido van Rossum470be141995-03-17 16:07:09 +0000221 case-insensitive matching; see the \code{casefold} data item below.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000222
223 The sequence
224
Fred Drake19479911998-02-13 06:58:54 +0000225\begin{verbatim}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000226prog = regex.compile(pat)
227result = prog.match(str)
Fred Drake19479911998-02-13 06:58:54 +0000228\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000229%
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000230is equivalent to
231
Fred Drake19479911998-02-13 06:58:54 +0000232\begin{verbatim}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000233result = regex.match(pat, str)
Fred Drake19479911998-02-13 06:58:54 +0000234\end{verbatim}
Fred Drake054f8fd1998-01-12 18:28:20 +0000235
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000236but the version using \code{compile()} is more efficient when multiple
237regular expressions are used concurrently in a single program. (The
238compiled version of the last pattern passed to \code{regex.match()} or
239\code{regex.search()} is cached, so programs that use only a single
240regular expression at a time needn't worry about compiling regular
241expressions.)
242\end{funcdesc}
243
244\begin{funcdesc}{set_syntax}{flags}
Fred Drake054f8fd1998-01-12 18:28:20 +0000245 Set the syntax to be used by future calls to \code{compile()},
246 \code{match()} and \code{search()}. (Already compiled expression
247 objects are not affected.) The argument is an integer which is the
248 OR of several flag bits. The return value is the previous value of
249 the syntax flags. Names for the flags are defined in the standard
250 module \code{regex_syntax}\refstmodindex{regex_syntax}; read the
251 file \file{regex_syntax.py} for more information.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000252\end{funcdesc}
253
Barry Warsawcd77df61997-02-18 18:54:30 +0000254\begin{funcdesc}{get_syntax}{}
255 Returns the current value of the syntax flags as an integer.
256\end{funcdesc}
257
Fred Drakecce10901998-03-17 06:33:25 +0000258\begin{funcdesc}{symcomp}{pattern\optional{, translate}}
Fred Drake054f8fd1998-01-12 18:28:20 +0000259This is like \code{compile()}, but supports symbolic group names: if a
Guido van Rossum6c4f0031995-03-07 10:14:09 +0000260parenthesis-enclosed group begins with a group name in angular
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000261brackets, e.g. \code{'\e(<id>[a-z][a-z0-9]*\e)'}, the group can
Fred Drake054f8fd1998-01-12 18:28:20 +0000262be referenced by its name in arguments to the \code{group()} method of
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000263the resulting compiled regular expression object, like this:
Guido van Rossum7defee71995-02-27 17:52:35 +0000264\code{p.group('id')}. Group names may contain alphanumeric characters
265and \code{'_'} only.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000266\end{funcdesc}
267
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000268\begin{excdesc}{error}
269 Exception raised when a string passed to one of the functions here
270 is not a valid regular expression (e.g., unmatched parentheses) or
271 when some other error occurs during compilation or matching. (It is
272 never an error if a string contains no match for a pattern.)
273\end{excdesc}
274
275\begin{datadesc}{casefold}
Fred Drake054f8fd1998-01-12 18:28:20 +0000276A string suitable to pass as the \var{translate} argument to
277\code{compile()} to map all upper case characters to their lowercase
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000278equivalents.
279\end{datadesc}
280
281\noindent
282Compiled regular expression objects support these methods:
283
Fred Drake19479911998-02-13 06:58:54 +0000284\setindexsubitem{(regex method)}
Fred Drakecce10901998-03-17 06:33:25 +0000285\begin{funcdesc}{match}{string\optional{, pos}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000286 Return how many characters at the beginning of \var{string} match
287 the compiled regular expression. Return \code{-1} if the string
288 does not match the pattern (this is different from a zero-length
289 match!).
290
Fred Drake054f8fd1998-01-12 18:28:20 +0000291 The optional second parameter, \var{pos}, gives an index in the string
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000292 where the search is to start; it defaults to \code{0}. This is not
293 completely equivalent to slicing the string; the \code{'\^'} pattern
Andrew M. Kuchling65b78631998-06-22 15:02:42 +0000294 character matches at the real beginning of the string and at positions
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000295 just after a newline, not necessarily at the index where the search
296 is to start.
297\end{funcdesc}
298
Fred Drakecce10901998-03-17 06:33:25 +0000299\begin{funcdesc}{search}{string\optional{, pos}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000300 Return the first position in \var{string} that matches the regular
301 expression \code{pattern}. Return \code{-1} if no position in the
302 string matches the pattern (this is different from a zero-length
303 match anywhere!).
304
305 The optional second parameter has the same meaning as for the
Fred Drake054f8fd1998-01-12 18:28:20 +0000306 \code{match()} method.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000307\end{funcdesc}
308
Fred Drakecce10901998-03-17 06:33:25 +0000309\begin{funcdesc}{group}{index, index, ...}
Fred Drake054f8fd1998-01-12 18:28:20 +0000310This method is only valid when the last call to the \code{match()}
311or \code{search()} method found a match. It returns one or more
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000312groups of the match. If there is a single \var{index} argument,
313the result is a single string; if there are multiple arguments, the
314result is a tuple with one item per argument. If the \var{index} is
315zero, the corresponding return value is the entire matching string; if
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000316it is in the inclusive range [1..99], it is the string matching the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000317the corresponding parenthesized group (using the default syntax,
Fred Drake875c8071998-01-02 02:50:13 +0000318groups are parenthesized using \code{{\e}(} and \code{{\e})}). If no
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000319such group exists, the corresponding result is \code{None}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000320
Fred Drake054f8fd1998-01-12 18:28:20 +0000321If the regular expression was compiled by \code{symcomp()} instead of
322\code{compile()}, the \var{index} arguments may also be strings
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000323identifying groups by their group name.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000324\end{funcdesc}
325
326\noindent
327Compiled regular expressions support these data attributes:
328
Fred Drake19479911998-02-13 06:58:54 +0000329\setindexsubitem{(regex attribute)}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000330
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000331\begin{datadesc}{regs}
Fred Drake054f8fd1998-01-12 18:28:20 +0000332When the last call to the \code{match()} or \code{search()} method found a
333match, this is a tuple of pairs of indexes corresponding to the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000334beginning and end of all parenthesized groups in the pattern. Indices
Fred Drake054f8fd1998-01-12 18:28:20 +0000335are relative to the string argument passed to \code{match()} or
336\code{search()}. The 0-th tuple gives the beginning and end or the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000337whole pattern. When the last match or search failed, this is
338\code{None}.
339\end{datadesc}
340
341\begin{datadesc}{last}
Fred Drake054f8fd1998-01-12 18:28:20 +0000342When the last call to the \code{match()} or \code{search()} method found a
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000343match, this is the string argument passed to that method. When the
344last match or search failed, this is \code{None}.
345\end{datadesc}
346
347\begin{datadesc}{translate}
348This is the value of the \var{translate} argument to
Fred Drake054f8fd1998-01-12 18:28:20 +0000349\code{regex.compile()} that created this regular expression object. If
350the \var{translate} argument was omitted in the \code{regex.compile()}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000351call, this is \code{None}.
352\end{datadesc}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000353
354\begin{datadesc}{givenpat}
Fred Drake054f8fd1998-01-12 18:28:20 +0000355The regular expression pattern as passed to \code{compile()} or
356\code{symcomp()}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000357\end{datadesc}
358
359\begin{datadesc}{realpat}
360The regular expression after stripping the group names for regular
Fred Drake054f8fd1998-01-12 18:28:20 +0000361expressions compiled with \code{symcomp()}. Same as \code{givenpat}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000362otherwise.
363\end{datadesc}
364
365\begin{datadesc}{groupindex}
366A dictionary giving the mapping from symbolic group names to numerical
Fred Drake054f8fd1998-01-12 18:28:20 +0000367group indexes for regular expressions compiled with \code{symcomp()}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000368\code{None} otherwise.
369\end{datadesc}