blob: f427a885280699d5e4124bae0e4fa8f0edcf6463 [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
Fred Drake19479911998-02-13 06:58:54 +0000193\setindexsubitem{(in module regex)}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000194
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000195\begin{funcdesc}{match}{pattern\, string}
196 Return how many characters at the beginning of \var{string} match
197 the regular expression \var{pattern}. Return \code{-1} if the
198 string does not match the pattern (this is different from a
199 zero-length match!).
200\end{funcdesc}
201
202\begin{funcdesc}{search}{pattern\, string}
203 Return the first position in \var{string} that matches the regular
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000204 expression \var{pattern}. Return \code{-1} if no position in the string
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000205 matches the pattern (this is different from a zero-length match
206 anywhere!).
207\end{funcdesc}
208
Guido van Rossum16d6e711994-08-08 12:30:22 +0000209\begin{funcdesc}{compile}{pattern\optional{\, translate}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000210 Compile a regular expression pattern into a regular expression
Fred Drake054f8fd1998-01-12 18:28:20 +0000211 object, which can be used for matching using its \code{match()} and
212 \code{search()} methods, described below. The optional argument
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000213 \var{translate}, if present, must be a 256-character string
214 indicating how characters (both of the pattern and of the strings to
Fred Drake054f8fd1998-01-12 18:28:20 +0000215 be matched) are translated before comparing them; the \var{i}-th
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000216 element of the string gives the translation for the character with
Fred Drake054f8fd1998-01-12 18:28:20 +0000217 \ASCII{} code \var{i}. This can be used to implement
Guido van Rossum470be141995-03-17 16:07:09 +0000218 case-insensitive matching; see the \code{casefold} data item below.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000219
220 The sequence
221
Fred Drake19479911998-02-13 06:58:54 +0000222\begin{verbatim}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000223prog = regex.compile(pat)
224result = prog.match(str)
Fred Drake19479911998-02-13 06:58:54 +0000225\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000226%
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000227is equivalent to
228
Fred Drake19479911998-02-13 06:58:54 +0000229\begin{verbatim}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000230result = regex.match(pat, str)
Fred Drake19479911998-02-13 06:58:54 +0000231\end{verbatim}
Fred Drake054f8fd1998-01-12 18:28:20 +0000232
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000233but the version using \code{compile()} is more efficient when multiple
234regular expressions are used concurrently in a single program. (The
235compiled version of the last pattern passed to \code{regex.match()} or
236\code{regex.search()} is cached, so programs that use only a single
237regular expression at a time needn't worry about compiling regular
238expressions.)
239\end{funcdesc}
240
241\begin{funcdesc}{set_syntax}{flags}
Fred Drake054f8fd1998-01-12 18:28:20 +0000242 Set the syntax to be used by future calls to \code{compile()},
243 \code{match()} and \code{search()}. (Already compiled expression
244 objects are not affected.) The argument is an integer which is the
245 OR of several flag bits. The return value is the previous value of
246 the syntax flags. Names for the flags are defined in the standard
247 module \code{regex_syntax}\refstmodindex{regex_syntax}; read the
248 file \file{regex_syntax.py} for more information.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000249\end{funcdesc}
250
Barry Warsawcd77df61997-02-18 18:54:30 +0000251\begin{funcdesc}{get_syntax}{}
252 Returns the current value of the syntax flags as an integer.
253\end{funcdesc}
254
Guido van Rossum16d6e711994-08-08 12:30:22 +0000255\begin{funcdesc}{symcomp}{pattern\optional{\, translate}}
Fred Drake054f8fd1998-01-12 18:28:20 +0000256This is like \code{compile()}, but supports symbolic group names: if a
Guido van Rossum6c4f0031995-03-07 10:14:09 +0000257parenthesis-enclosed group begins with a group name in angular
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000258brackets, e.g. \code{'\e(<id>[a-z][a-z0-9]*\e)'}, the group can
Fred Drake054f8fd1998-01-12 18:28:20 +0000259be referenced by its name in arguments to the \code{group()} method of
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000260the resulting compiled regular expression object, like this:
Guido van Rossum7defee71995-02-27 17:52:35 +0000261\code{p.group('id')}. Group names may contain alphanumeric characters
262and \code{'_'} only.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000263\end{funcdesc}
264
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000265\begin{excdesc}{error}
266 Exception raised when a string passed to one of the functions here
267 is not a valid regular expression (e.g., unmatched parentheses) or
268 when some other error occurs during compilation or matching. (It is
269 never an error if a string contains no match for a pattern.)
270\end{excdesc}
271
272\begin{datadesc}{casefold}
Fred Drake054f8fd1998-01-12 18:28:20 +0000273A string suitable to pass as the \var{translate} argument to
274\code{compile()} to map all upper case characters to their lowercase
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000275equivalents.
276\end{datadesc}
277
278\noindent
279Compiled regular expression objects support these methods:
280
Fred Drake19479911998-02-13 06:58:54 +0000281\setindexsubitem{(regex method)}
Guido van Rossum16d6e711994-08-08 12:30:22 +0000282\begin{funcdesc}{match}{string\optional{\, pos}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000283 Return how many characters at the beginning of \var{string} match
284 the compiled regular expression. Return \code{-1} if the string
285 does not match the pattern (this is different from a zero-length
286 match!).
287
Fred Drake054f8fd1998-01-12 18:28:20 +0000288 The optional second parameter, \var{pos}, gives an index in the string
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000289 where the search is to start; it defaults to \code{0}. This is not
290 completely equivalent to slicing the string; the \code{'\^'} pattern
291 character matches at the real begin of the string and at positions
292 just after a newline, not necessarily at the index where the search
293 is to start.
294\end{funcdesc}
295
Guido van Rossum16d6e711994-08-08 12:30:22 +0000296\begin{funcdesc}{search}{string\optional{\, pos}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000297 Return the first position in \var{string} that matches the regular
298 expression \code{pattern}. Return \code{-1} if no position in the
299 string matches the pattern (this is different from a zero-length
300 match anywhere!).
301
302 The optional second parameter has the same meaning as for the
Fred Drake054f8fd1998-01-12 18:28:20 +0000303 \code{match()} method.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000304\end{funcdesc}
305
306\begin{funcdesc}{group}{index\, index\, ...}
Fred Drake054f8fd1998-01-12 18:28:20 +0000307This method is only valid when the last call to the \code{match()}
308or \code{search()} method found a match. It returns one or more
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000309groups of the match. If there is a single \var{index} argument,
310the result is a single string; if there are multiple arguments, the
311result is a tuple with one item per argument. If the \var{index} is
312zero, the corresponding return value is the entire matching string; if
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000313it is in the inclusive range [1..99], it is the string matching the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000314the corresponding parenthesized group (using the default syntax,
Fred Drake875c8071998-01-02 02:50:13 +0000315groups are parenthesized using \code{{\e}(} and \code{{\e})}). If no
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000316such group exists, the corresponding result is \code{None}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000317
Fred Drake054f8fd1998-01-12 18:28:20 +0000318If the regular expression was compiled by \code{symcomp()} instead of
319\code{compile()}, the \var{index} arguments may also be strings
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000320identifying groups by their group name.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000321\end{funcdesc}
322
323\noindent
324Compiled regular expressions support these data attributes:
325
Fred Drake19479911998-02-13 06:58:54 +0000326\setindexsubitem{(regex attribute)}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000327
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000328\begin{datadesc}{regs}
Fred Drake054f8fd1998-01-12 18:28:20 +0000329When the last call to the \code{match()} or \code{search()} method found a
330match, this is a tuple of pairs of indexes corresponding to the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000331beginning and end of all parenthesized groups in the pattern. Indices
Fred Drake054f8fd1998-01-12 18:28:20 +0000332are relative to the string argument passed to \code{match()} or
333\code{search()}. The 0-th tuple gives the beginning and end or the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000334whole pattern. When the last match or search failed, this is
335\code{None}.
336\end{datadesc}
337
338\begin{datadesc}{last}
Fred Drake054f8fd1998-01-12 18:28:20 +0000339When the last call to the \code{match()} or \code{search()} method found a
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000340match, this is the string argument passed to that method. When the
341last match or search failed, this is \code{None}.
342\end{datadesc}
343
344\begin{datadesc}{translate}
345This is the value of the \var{translate} argument to
Fred Drake054f8fd1998-01-12 18:28:20 +0000346\code{regex.compile()} that created this regular expression object. If
347the \var{translate} argument was omitted in the \code{regex.compile()}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000348call, this is \code{None}.
349\end{datadesc}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000350
351\begin{datadesc}{givenpat}
Fred Drake054f8fd1998-01-12 18:28:20 +0000352The regular expression pattern as passed to \code{compile()} or
353\code{symcomp()}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000354\end{datadesc}
355
356\begin{datadesc}{realpat}
357The regular expression after stripping the group names for regular
Fred Drake054f8fd1998-01-12 18:28:20 +0000358expressions compiled with \code{symcomp()}. Same as \code{givenpat}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000359otherwise.
360\end{datadesc}
361
362\begin{datadesc}{groupindex}
363A dictionary giving the mapping from symbolic group names to numerical
Fred Drake054f8fd1998-01-12 18:28:20 +0000364group indexes for regular expressions compiled with \code{symcomp()}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000365\code{None} otherwise.
366\end{datadesc}