blob: 253d50bcd85344478c6b6266b822190d352100b2 [file] [log] [blame]
Fred Drake3a0351c1998-04-04 07:23:21 +00001\section{Built-in Module \module{regex}}
Fred Drakeb91e9341998-07-23 17:59:49 +00002\declaremodule{builtin}{regex}
3
4\modulesynopsis{Regular expression search and match operations.}
5
Fred Drake054f8fd1998-01-12 18:28:20 +00006
Guido van Rossum5fdeeea1994-01-02 01:22:07 +00007This module provides regular expression matching operations similar to
Guido van Rossum28f9a681997-12-09 19:45:47 +00008those found in Emacs.
9
10\strong{Obsolescence note:}
11This module is obsolete as of Python version 1.5; it is still being
12maintained because much existing code still uses it. All new code in
Fred Drake054f8fd1998-01-12 18:28:20 +000013need of regular expressions should use the new
14\code{re}\refstmodindex{re} module, which supports the more powerful
15and regular Perl-style regular expressions. Existing code should be
16converted. The standard library module
17\code{reconvert}\refstmodindex{reconvert} helps in converting
18\code{regex} style regular expressions to \code{re}\refstmodindex{re}
Fred Drake9da38811998-04-09 14:06:33 +000019style regular expressions. (For more conversion help, see Andrew
20Kuchling's\index{Kuchling, Andrew} ``\module{regex-to-re} HOWTO'' at
21\url{http://www.python.org/doc/howto/regex-to-re/}.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000022
Guido van Rossum6240b0b1996-10-24 22:49:13 +000023By default the patterns are Emacs-style regular expressions
24(with one exception). There is
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000025a way to change the syntax to match that of several well-known
Guido van Rossumfe4254e1995-08-11 00:31:57 +000026\UNIX{} utilities. The exception is that Emacs' \samp{\e s}
27pattern is not supported, since the original implementation references
28the Emacs syntax tables.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000029
30This module is 8-bit clean: both patterns and strings may contain null
31bytes and characters whose high bit is set.
32
Guido van Rossum326c0bc1994-01-03 00:00:31 +000033\strong{Please note:} There is a little-known fact about Python string
34literals which means that you don't usually have to worry about
35doubling backslashes, even though they are used to escape special
36characters in string literals as well as in regular expressions. This
37is because Python doesn't remove backslashes from string literals if
38they are followed by an unrecognized escape character.
39\emph{However}, if you want to include a literal \dfn{backslash} in a
40regular expression represented as a string literal, you have to
Guido van Rossum1f8cee21997-03-14 04:10:13 +000041\emph{quadruple} it or enclose it in a singleton character class.
42E.g.\ to extract \LaTeX\ \samp{\e section\{{\rm
Guido van Rossum326c0bc1994-01-03 00:00:31 +000043\ldots}\}} headers from a document, you can use this pattern:
Guido van Rossumeb0f0661997-12-30 20:38:16 +000044\code{'[\e ]section\{\e (.*\e )\}'}. \emph{Another exception:}
Guido van Rossum1a535601996-06-26 19:43:22 +000045the escape sequece \samp{\e b} is significant in string literals
46(where it means the ASCII bell character) as well as in Emacs regular
47expressions (where it stands for a word boundary), so in order to
48search for a word boundary, you should use the pattern \code{'\e \e b'}.
49Similarly, a backslash followed by a digit 0-7 should be doubled to
50avoid interpretation as an octal escape.
51
52\subsection{Regular Expressions}
53
54A regular expression (or RE) specifies a set of strings that matches
55it; the functions in this module let you check if a particular string
Guido van Rossum6240b0b1996-10-24 22:49:13 +000056matches a given regular expression (or if a given regular expression
57matches a particular string, which comes down to the same thing).
Guido van Rossum1a535601996-06-26 19:43:22 +000058
59Regular expressions can be concatenated to form new regular
60expressions; if \emph{A} and \emph{B} are both regular expressions,
61then \emph{AB} is also an regular expression. If a string \emph{p}
62matches A and another string \emph{q} matches B, the string \emph{pq}
63will match AB. Thus, complex expressions can easily be constructed
64from simpler ones like the primitives described here. For details of
65the theory and implementation of regular expressions, consult almost
66any textbook about compiler construction.
67
68% XXX The reference could be made more specific, say to
69% "Compilers: Principles, Techniques and Tools", by Alfred V. Aho,
70% Ravi Sethi, and Jeffrey D. Ullman, or some FA text.
71
Guido van Rossum6240b0b1996-10-24 22:49:13 +000072A brief explanation of the format of regular expressions follows.
Guido van Rossum1a535601996-06-26 19:43:22 +000073
74Regular expressions can contain both special and ordinary characters.
75Ordinary characters, like '\code{A}', '\code{a}', or '\code{0}', are
76the simplest regular expressions; they simply match themselves. You
77can concatenate ordinary characters, so '\code{last}' matches the
Guido van Rossum6240b0b1996-10-24 22:49:13 +000078characters 'last'. (In the rest of this section, we'll write RE's in
79\code{this special font}, usually without quotes, and strings to be
80matched 'in single quotes'.)
Guido van Rossum1a535601996-06-26 19:43:22 +000081
82Special characters either stand for classes of ordinary characters, or
83affect how the regular expressions around them are interpreted.
84
85The special characters are:
86\begin{itemize}
Fred Drake4b3f0311996-12-13 22:04:31 +000087\item[\code{.}] (Dot.) Matches any character except a newline.
88\item[\code{\^}] (Caret.) Matches the start of the string.
89\item[\code{\$}] Matches the end of the string.
Guido van Rossum1a535601996-06-26 19:43:22 +000090\code{foo} matches both 'foo' and 'foobar', while the regular
Fred Drake4b3f0311996-12-13 22:04:31 +000091expression '\code{foo\$}' matches only 'foo'.
Guido van Rossum1a535601996-06-26 19:43:22 +000092\item[\code{*}] Causes the resulting RE to
93match 0 or more repetitions of the preceding RE. \code{ab*} will
94match 'a', 'ab', or 'a' followed by any number of 'b's.
95\item[\code{+}] Causes the
96resulting RE to match 1 or more repetitions of the preceding RE.
97\code{ab+} will match 'a' followed by any non-zero number of 'b's; it
98will not match just 'a'.
99\item[\code{?}] Causes the resulting RE to
100match 0 or 1 repetitions of the preceding RE. \code{ab?} will
101match either 'a' or 'ab'.
102
103\item[\code{\e}] Either escapes special characters (permitting you to match
104characters like '*?+\&\$'), or signals a special sequence; special
105sequences are discussed below. Remember that Python also uses the
106backslash as an escape sequence in string literals; if the escape
107sequence isn't recognized by Python's parser, the backslash and
108subsequent character are included in the resulting string. However,
109if Python would recognize the resulting sequence, the backslash should
110be repeated twice.
111
112\item[\code{[]}] Used to indicate a set of characters. Characters can
113be listed individually, or a range is indicated by giving two
114characters and separating them by a '-'. Special characters are
115not active inside sets. For example, \code{[akm\$]}
116will match any of the characters 'a', 'k', 'm', or '\$'; \code{[a-z]} will
117match any lowercase letter.
118
119If you want to include a \code{]} inside a
120set, it must be the first character of the set; to include a \code{-},
121place it as the first or last character.
122
123Characters \emph{not} within a range can be matched by including a
124\code{\^} as the first character of the set; \code{\^} elsewhere will
125simply match the '\code{\^}' character.
126\end{itemize}
127
128The special sequences consist of '\code{\e}' and a character
129from the list below. If the ordinary character is not on the list,
130then the resulting RE will match the second character. For example,
131\code{\e\$} matches the character '\$'. Ones where the backslash
Guido van Rossumeb0f0661997-12-30 20:38:16 +0000132should be doubled in string literals are indicated.
Guido van Rossum1a535601996-06-26 19:43:22 +0000133
134\begin{itemize}
135\item[\code{\e|}]\code{A\e|B}, where A and B can be arbitrary REs,
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000136creates a regular expression that will match either A or B. This can
137be used inside groups (see below) as well.
Guido van Rossum1a535601996-06-26 19:43:22 +0000138%
Fred Drake4b3f0311996-12-13 22:04:31 +0000139\item[\code{\e( \e)}] Indicates the start and end of a group; the
Guido van Rossum1a535601996-06-26 19:43:22 +0000140contents of a group can be matched later in the string with the
Fred Drake4b3f0311996-12-13 22:04:31 +0000141\code{\e [1-9]} special sequence, described next.
Fred Drake75bfb0f1998-02-19 06:32:06 +0000142\end{itemize}
143
144\begin{fulllineitems}
145\item[\code{\e \e 1, ... \e \e 7, \e 8, \e 9}]
Fred Drake4b3f0311996-12-13 22:04:31 +0000146Matches the contents of the group of the same
Guido van Rossum1a535601996-06-26 19:43:22 +0000147number. For example, \code{\e (.+\e ) \e \e 1} matches 'the the' or
148'55 55', but not 'the end' (note the space after the group). This
149special sequence can only be used to match one of the first 9 groups;
150groups with higher numbers can be matched using the \code{\e v}
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000151sequence. (\code{\e 8} and \code{\e 9} don't need a double backslash
Guido van Rossum38e0df31998-02-11 22:55:55 +0000152because they are not octal digits.)
Fred Drake75bfb0f1998-02-19 06:32:06 +0000153\end{fulllineitems}
154
155\begin{itemize}
Fred Drake4b3f0311996-12-13 22:04:31 +0000156\item[\code{\e \e b}] Matches the empty string, but only at the
Guido van Rossum1a535601996-06-26 19:43:22 +0000157beginning or end of a word. A word is defined as a sequence of
158alphanumeric characters, so the end of a word is indicated by
Fred Drake4b3f0311996-12-13 22:04:31 +0000159whitespace or a non-alphanumeric character.
Guido van Rossum1a535601996-06-26 19:43:22 +0000160%
Fred Drake4b3f0311996-12-13 22:04:31 +0000161\item[\code{\e B}] Matches the empty string, but when it is \emph{not} at the
162beginning or end of a word.
Guido van Rossum1a535601996-06-26 19:43:22 +0000163%
Fred Drake4b3f0311996-12-13 22:04:31 +0000164\item[\code{\e v}] Must be followed by a two digit decimal number, and
Fred Drake054f8fd1998-01-12 18:28:20 +0000165matches the contents of the group of the same number. The group
166number must be between 1 and 99, inclusive.
Guido van Rossum1a535601996-06-26 19:43:22 +0000167%
168\item[\code{\e w}]Matches any alphanumeric character; this is
169equivalent to the set \code{[a-zA-Z0-9]}.
170%
Fred Drake4b3f0311996-12-13 22:04:31 +0000171\item[\code{\e W}] Matches any non-alphanumeric character; this is
172equivalent to the set \code{[\^a-zA-Z0-9]}.
173\item[\code{\e <}] Matches the empty string, but only at the beginning of a
Guido van Rossum1a535601996-06-26 19:43:22 +0000174word. A word is defined as a sequence of alphanumeric characters, so
175the end of a word is indicated by whitespace or a non-alphanumeric
Fred Drake4b3f0311996-12-13 22:04:31 +0000176character.
177\item[\code{\e >}] Matches the empty string, but only at the end of a
178word.
Guido van Rossum1a535601996-06-26 19:43:22 +0000179
Fred Drake4b3f0311996-12-13 22:04:31 +0000180\item[\code{\e \e \e \e}] Matches a literal backslash.
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000181
Guido van Rossum1a535601996-06-26 19:43:22 +0000182% In Emacs, the following two are start of buffer/end of buffer. In
183% Python they seem to be synonyms for ^$.
Fred Drake4b3f0311996-12-13 22:04:31 +0000184\item[\code{\e `}] Like \code{\^}, this only matches at the start of the
185string.
Fred Drake054f8fd1998-01-12 18:28:20 +0000186\item[\code{\e \e '}] Like \code{\$}, this only matches at the end of
187the string.
Guido van Rossum1a535601996-06-26 19:43:22 +0000188% end of buffer
189\end{itemize}
190
191\subsection{Module Contents}
Guido van Rossum38e0df31998-02-11 22:55:55 +0000192\nodename{Contents of Module regex}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000193
194The module defines these functions, and an exception:
195
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000196
Fred Drakecce10901998-03-17 06:33:25 +0000197\begin{funcdesc}{match}{pattern, string}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000198 Return how many characters at the beginning of \var{string} match
199 the regular expression \var{pattern}. Return \code{-1} if the
200 string does not match the pattern (this is different from a
201 zero-length match!).
202\end{funcdesc}
203
Fred Drakecce10901998-03-17 06:33:25 +0000204\begin{funcdesc}{search}{pattern, string}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000205 Return the first position in \var{string} that matches the regular
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000206 expression \var{pattern}. Return \code{-1} if no position in the string
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000207 matches the pattern (this is different from a zero-length match
208 anywhere!).
209\end{funcdesc}
210
Fred Drakecce10901998-03-17 06:33:25 +0000211\begin{funcdesc}{compile}{pattern\optional{, translate}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000212 Compile a regular expression pattern into a regular expression
Fred Drake054f8fd1998-01-12 18:28:20 +0000213 object, which can be used for matching using its \code{match()} and
214 \code{search()} methods, described below. The optional argument
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000215 \var{translate}, if present, must be a 256-character string
216 indicating how characters (both of the pattern and of the strings to
Fred Drake054f8fd1998-01-12 18:28:20 +0000217 be matched) are translated before comparing them; the \var{i}-th
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000218 element of the string gives the translation for the character with
Fred Drake054f8fd1998-01-12 18:28:20 +0000219 \ASCII{} code \var{i}. This can be used to implement
Guido van Rossum470be141995-03-17 16:07:09 +0000220 case-insensitive matching; see the \code{casefold} data item below.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000221
222 The sequence
223
Fred Drake19479911998-02-13 06:58:54 +0000224\begin{verbatim}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000225prog = regex.compile(pat)
226result = prog.match(str)
Fred Drake19479911998-02-13 06:58:54 +0000227\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000228%
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000229is equivalent to
230
Fred Drake19479911998-02-13 06:58:54 +0000231\begin{verbatim}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000232result = regex.match(pat, str)
Fred Drake19479911998-02-13 06:58:54 +0000233\end{verbatim}
Fred Drake054f8fd1998-01-12 18:28:20 +0000234
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000235but the version using \code{compile()} is more efficient when multiple
236regular expressions are used concurrently in a single program. (The
237compiled version of the last pattern passed to \code{regex.match()} or
238\code{regex.search()} is cached, so programs that use only a single
239regular expression at a time needn't worry about compiling regular
240expressions.)
241\end{funcdesc}
242
243\begin{funcdesc}{set_syntax}{flags}
Fred Drake054f8fd1998-01-12 18:28:20 +0000244 Set the syntax to be used by future calls to \code{compile()},
245 \code{match()} and \code{search()}. (Already compiled expression
246 objects are not affected.) The argument is an integer which is the
247 OR of several flag bits. The return value is the previous value of
248 the syntax flags. Names for the flags are defined in the standard
249 module \code{regex_syntax}\refstmodindex{regex_syntax}; read the
250 file \file{regex_syntax.py} for more information.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000251\end{funcdesc}
252
Barry Warsawcd77df61997-02-18 18:54:30 +0000253\begin{funcdesc}{get_syntax}{}
254 Returns the current value of the syntax flags as an integer.
255\end{funcdesc}
256
Fred Drakecce10901998-03-17 06:33:25 +0000257\begin{funcdesc}{symcomp}{pattern\optional{, translate}}
Fred Drake054f8fd1998-01-12 18:28:20 +0000258This is like \code{compile()}, but supports symbolic group names: if a
Guido van Rossum6c4f0031995-03-07 10:14:09 +0000259parenthesis-enclosed group begins with a group name in angular
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000260brackets, e.g. \code{'\e(<id>[a-z][a-z0-9]*\e)'}, the group can
Fred Drake054f8fd1998-01-12 18:28:20 +0000261be referenced by its name in arguments to the \code{group()} method of
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000262the resulting compiled regular expression object, like this:
Guido van Rossum7defee71995-02-27 17:52:35 +0000263\code{p.group('id')}. Group names may contain alphanumeric characters
264and \code{'_'} only.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000265\end{funcdesc}
266
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000267\begin{excdesc}{error}
268 Exception raised when a string passed to one of the functions here
269 is not a valid regular expression (e.g., unmatched parentheses) or
270 when some other error occurs during compilation or matching. (It is
271 never an error if a string contains no match for a pattern.)
272\end{excdesc}
273
274\begin{datadesc}{casefold}
Fred Drake054f8fd1998-01-12 18:28:20 +0000275A string suitable to pass as the \var{translate} argument to
276\code{compile()} to map all upper case characters to their lowercase
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000277equivalents.
278\end{datadesc}
279
280\noindent
281Compiled regular expression objects support these methods:
282
Fred Drake19479911998-02-13 06:58:54 +0000283\setindexsubitem{(regex method)}
Fred Drakecce10901998-03-17 06:33:25 +0000284\begin{funcdesc}{match}{string\optional{, pos}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000285 Return how many characters at the beginning of \var{string} match
286 the compiled regular expression. Return \code{-1} if the string
287 does not match the pattern (this is different from a zero-length
288 match!).
289
Fred Drake054f8fd1998-01-12 18:28:20 +0000290 The optional second parameter, \var{pos}, gives an index in the string
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000291 where the search is to start; it defaults to \code{0}. This is not
292 completely equivalent to slicing the string; the \code{'\^'} pattern
Andrew M. Kuchling65b78631998-06-22 15:02:42 +0000293 character matches at the real beginning of the string and at positions
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000294 just after a newline, not necessarily at the index where the search
295 is to start.
296\end{funcdesc}
297
Fred Drakecce10901998-03-17 06:33:25 +0000298\begin{funcdesc}{search}{string\optional{, pos}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000299 Return the first position in \var{string} that matches the regular
300 expression \code{pattern}. Return \code{-1} if no position in the
301 string matches the pattern (this is different from a zero-length
302 match anywhere!).
303
304 The optional second parameter has the same meaning as for the
Fred Drake054f8fd1998-01-12 18:28:20 +0000305 \code{match()} method.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000306\end{funcdesc}
307
Fred Drakecce10901998-03-17 06:33:25 +0000308\begin{funcdesc}{group}{index, index, ...}
Fred Drake054f8fd1998-01-12 18:28:20 +0000309This method is only valid when the last call to the \code{match()}
310or \code{search()} method found a match. It returns one or more
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000311groups of the match. If there is a single \var{index} argument,
312the result is a single string; if there are multiple arguments, the
313result is a tuple with one item per argument. If the \var{index} is
314zero, the corresponding return value is the entire matching string; if
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000315it is in the inclusive range [1..99], it is the string matching the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000316the corresponding parenthesized group (using the default syntax,
Fred Drake875c8071998-01-02 02:50:13 +0000317groups are parenthesized using \code{{\e}(} and \code{{\e})}). If no
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000318such group exists, the corresponding result is \code{None}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000319
Fred Drake054f8fd1998-01-12 18:28:20 +0000320If the regular expression was compiled by \code{symcomp()} instead of
321\code{compile()}, the \var{index} arguments may also be strings
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000322identifying groups by their group name.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000323\end{funcdesc}
324
325\noindent
326Compiled regular expressions support these data attributes:
327
Fred Drake19479911998-02-13 06:58:54 +0000328\setindexsubitem{(regex attribute)}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000329
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000330\begin{datadesc}{regs}
Fred Drake054f8fd1998-01-12 18:28:20 +0000331When the last call to the \code{match()} or \code{search()} method found a
332match, this is a tuple of pairs of indexes corresponding to the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000333beginning and end of all parenthesized groups in the pattern. Indices
Fred Drake054f8fd1998-01-12 18:28:20 +0000334are relative to the string argument passed to \code{match()} or
335\code{search()}. The 0-th tuple gives the beginning and end or the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000336whole pattern. When the last match or search failed, this is
337\code{None}.
338\end{datadesc}
339
340\begin{datadesc}{last}
Fred Drake054f8fd1998-01-12 18:28:20 +0000341When the last call to the \code{match()} or \code{search()} method found a
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000342match, this is the string argument passed to that method. When the
343last match or search failed, this is \code{None}.
344\end{datadesc}
345
346\begin{datadesc}{translate}
347This is the value of the \var{translate} argument to
Fred Drake054f8fd1998-01-12 18:28:20 +0000348\code{regex.compile()} that created this regular expression object. If
349the \var{translate} argument was omitted in the \code{regex.compile()}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000350call, this is \code{None}.
351\end{datadesc}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000352
353\begin{datadesc}{givenpat}
Fred Drake054f8fd1998-01-12 18:28:20 +0000354The regular expression pattern as passed to \code{compile()} or
355\code{symcomp()}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000356\end{datadesc}
357
358\begin{datadesc}{realpat}
359The regular expression after stripping the group names for regular
Fred Drake054f8fd1998-01-12 18:28:20 +0000360expressions compiled with \code{symcomp()}. Same as \code{givenpat}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000361otherwise.
362\end{datadesc}
363
364\begin{datadesc}{groupindex}
365A dictionary giving the mapping from symbolic group names to numerical
Fred Drake054f8fd1998-01-12 18:28:20 +0000366group indexes for regular expressions compiled with \code{symcomp()}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000367\code{None} otherwise.
368\end{datadesc}