blob: ee1563d566307c8fbdf6743423ede7ac695b6fc9 [file] [log] [blame]
Guido van Rossum5fdeeea1994-01-02 01:22:07 +00001\section{Built-in Module \sectcode{regex}}
Guido van Rossume47da0a1997-07-17 16:34:52 +00002\label{module-regex}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +00003
4\bimodindex{regex}
5This module provides regular expression matching operations similar to
6those found in Emacs. It is always available.
7
Guido van Rossum6240b0b1996-10-24 22:49:13 +00008By default the patterns are Emacs-style regular expressions
9(with one exception). There is
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000010a way to change the syntax to match that of several well-known
Guido van Rossumfe4254e1995-08-11 00:31:57 +000011\UNIX{} utilities. The exception is that Emacs' \samp{\e s}
12pattern is not supported, since the original implementation references
13the Emacs syntax tables.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000014
15This module is 8-bit clean: both patterns and strings may contain null
16bytes and characters whose high bit is set.
17
Guido van Rossum326c0bc1994-01-03 00:00:31 +000018\strong{Please note:} There is a little-known fact about Python string
19literals which means that you don't usually have to worry about
20doubling backslashes, even though they are used to escape special
21characters in string literals as well as in regular expressions. This
22is because Python doesn't remove backslashes from string literals if
23they are followed by an unrecognized escape character.
24\emph{However}, if you want to include a literal \dfn{backslash} in a
25regular expression represented as a string literal, you have to
Guido van Rossum1f8cee21997-03-14 04:10:13 +000026\emph{quadruple} it or enclose it in a singleton character class.
27E.g.\ to extract \LaTeX\ \samp{\e section\{{\rm
Guido van Rossum326c0bc1994-01-03 00:00:31 +000028\ldots}\}} headers from a document, you can use this pattern:
Guido van Rossum1f8cee21997-03-14 04:10:13 +000029\code{'[\e ] section\{\e (.*\e )\}'}. \emph{Another exception:}
Guido van Rossum1a535601996-06-26 19:43:22 +000030the escape sequece \samp{\e b} is significant in string literals
31(where it means the ASCII bell character) as well as in Emacs regular
32expressions (where it stands for a word boundary), so in order to
33search for a word boundary, you should use the pattern \code{'\e \e b'}.
34Similarly, a backslash followed by a digit 0-7 should be doubled to
35avoid interpretation as an octal escape.
36
37\subsection{Regular Expressions}
38
39A regular expression (or RE) specifies a set of strings that matches
40it; the functions in this module let you check if a particular string
Guido van Rossum6240b0b1996-10-24 22:49:13 +000041matches a given regular expression (or if a given regular expression
42matches a particular string, which comes down to the same thing).
Guido van Rossum1a535601996-06-26 19:43:22 +000043
44Regular expressions can be concatenated to form new regular
45expressions; if \emph{A} and \emph{B} are both regular expressions,
46then \emph{AB} is also an regular expression. If a string \emph{p}
47matches A and another string \emph{q} matches B, the string \emph{pq}
48will match AB. Thus, complex expressions can easily be constructed
49from simpler ones like the primitives described here. For details of
50the theory and implementation of regular expressions, consult almost
51any textbook about compiler construction.
52
53% XXX The reference could be made more specific, say to
54% "Compilers: Principles, Techniques and Tools", by Alfred V. Aho,
55% Ravi Sethi, and Jeffrey D. Ullman, or some FA text.
56
Guido van Rossum6240b0b1996-10-24 22:49:13 +000057A brief explanation of the format of regular expressions follows.
Guido van Rossum1a535601996-06-26 19:43:22 +000058
59Regular expressions can contain both special and ordinary characters.
60Ordinary characters, like '\code{A}', '\code{a}', or '\code{0}', are
61the simplest regular expressions; they simply match themselves. You
62can concatenate ordinary characters, so '\code{last}' matches the
Guido van Rossum6240b0b1996-10-24 22:49:13 +000063characters 'last'. (In the rest of this section, we'll write RE's in
64\code{this special font}, usually without quotes, and strings to be
65matched 'in single quotes'.)
Guido van Rossum1a535601996-06-26 19:43:22 +000066
67Special characters either stand for classes of ordinary characters, or
68affect how the regular expressions around them are interpreted.
69
70The special characters are:
71\begin{itemize}
Fred Drake4b3f0311996-12-13 22:04:31 +000072\item[\code{.}] (Dot.) Matches any character except a newline.
73\item[\code{\^}] (Caret.) Matches the start of the string.
74\item[\code{\$}] Matches the end of the string.
Guido van Rossum1a535601996-06-26 19:43:22 +000075\code{foo} matches both 'foo' and 'foobar', while the regular
Fred Drake4b3f0311996-12-13 22:04:31 +000076expression '\code{foo\$}' matches only 'foo'.
Guido van Rossum1a535601996-06-26 19:43:22 +000077\item[\code{*}] Causes the resulting RE to
78match 0 or more repetitions of the preceding RE. \code{ab*} will
79match 'a', 'ab', or 'a' followed by any number of 'b's.
80\item[\code{+}] Causes the
81resulting RE to match 1 or more repetitions of the preceding RE.
82\code{ab+} will match 'a' followed by any non-zero number of 'b's; it
83will not match just 'a'.
84\item[\code{?}] Causes the resulting RE to
85match 0 or 1 repetitions of the preceding RE. \code{ab?} will
86match either 'a' or 'ab'.
87
88\item[\code{\e}] Either escapes special characters (permitting you to match
89characters like '*?+\&\$'), or signals a special sequence; special
90sequences are discussed below. Remember that Python also uses the
91backslash as an escape sequence in string literals; if the escape
92sequence isn't recognized by Python's parser, the backslash and
93subsequent character are included in the resulting string. However,
94if Python would recognize the resulting sequence, the backslash should
95be repeated twice.
96
97\item[\code{[]}] Used to indicate a set of characters. Characters can
98be listed individually, or a range is indicated by giving two
99characters and separating them by a '-'. Special characters are
100not active inside sets. For example, \code{[akm\$]}
101will match any of the characters 'a', 'k', 'm', or '\$'; \code{[a-z]} will
102match any lowercase letter.
103
104If you want to include a \code{]} inside a
105set, it must be the first character of the set; to include a \code{-},
106place it as the first or last character.
107
108Characters \emph{not} within a range can be matched by including a
109\code{\^} as the first character of the set; \code{\^} elsewhere will
110simply match the '\code{\^}' character.
111\end{itemize}
112
113The special sequences consist of '\code{\e}' and a character
114from the list below. If the ordinary character is not on the list,
115then the resulting RE will match the second character. For example,
116\code{\e\$} matches the character '\$'. Ones where the backslash
117should be doubled are indicated.
118
119\begin{itemize}
120\item[\code{\e|}]\code{A\e|B}, where A and B can be arbitrary REs,
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000121creates a regular expression that will match either A or B. This can
122be used inside groups (see below) as well.
Guido van Rossum1a535601996-06-26 19:43:22 +0000123%
Fred Drake4b3f0311996-12-13 22:04:31 +0000124\item[\code{\e( \e)}] Indicates the start and end of a group; the
Guido van Rossum1a535601996-06-26 19:43:22 +0000125contents of a group can be matched later in the string with the
Fred Drake4b3f0311996-12-13 22:04:31 +0000126\code{\e [1-9]} special sequence, described next.
Guido van Rossum1a535601996-06-26 19:43:22 +0000127%
128{\fulllineitems\item[\code{\e \e 1, ... \e \e 7, \e 8, \e 9}]
Fred Drake4b3f0311996-12-13 22:04:31 +0000129Matches the contents of the group of the same
Guido van Rossum1a535601996-06-26 19:43:22 +0000130number. For example, \code{\e (.+\e ) \e \e 1} matches 'the the' or
131'55 55', but not 'the end' (note the space after the group). This
132special sequence can only be used to match one of the first 9 groups;
133groups with higher numbers can be matched using the \code{\e v}
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000134sequence. (\code{\e 8} and \code{\e 9} don't need a double backslash
Fred Drake4b3f0311996-12-13 22:04:31 +0000135because they are not octal digits.)}
Guido van Rossum1a535601996-06-26 19:43:22 +0000136%
Fred Drake4b3f0311996-12-13 22:04:31 +0000137\item[\code{\e \e b}] Matches the empty string, but only at the
Guido van Rossum1a535601996-06-26 19:43:22 +0000138beginning or end of a word. A word is defined as a sequence of
139alphanumeric characters, so the end of a word is indicated by
Fred Drake4b3f0311996-12-13 22:04:31 +0000140whitespace or a non-alphanumeric character.
Guido van Rossum1a535601996-06-26 19:43:22 +0000141%
Fred Drake4b3f0311996-12-13 22:04:31 +0000142\item[\code{\e B}] Matches the empty string, but when it is \emph{not} at the
143beginning or end of a word.
Guido van Rossum1a535601996-06-26 19:43:22 +0000144%
Fred Drake4b3f0311996-12-13 22:04:31 +0000145\item[\code{\e v}] Must be followed by a two digit decimal number, and
146matches the contents of the group of the same number. The group number must be between 1 and 99, inclusive.
Guido van Rossum1a535601996-06-26 19:43:22 +0000147%
148\item[\code{\e w}]Matches any alphanumeric character; this is
149equivalent to the set \code{[a-zA-Z0-9]}.
150%
Fred Drake4b3f0311996-12-13 22:04:31 +0000151\item[\code{\e W}] Matches any non-alphanumeric character; this is
152equivalent to the set \code{[\^a-zA-Z0-9]}.
153\item[\code{\e <}] Matches the empty string, but only at the beginning of a
Guido van Rossum1a535601996-06-26 19:43:22 +0000154word. A word is defined as a sequence of alphanumeric characters, so
155the end of a word is indicated by whitespace or a non-alphanumeric
Fred Drake4b3f0311996-12-13 22:04:31 +0000156character.
157\item[\code{\e >}] Matches the empty string, but only at the end of a
158word.
Guido van Rossum1a535601996-06-26 19:43:22 +0000159
Fred Drake4b3f0311996-12-13 22:04:31 +0000160\item[\code{\e \e \e \e}] Matches a literal backslash.
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000161
Guido van Rossum1a535601996-06-26 19:43:22 +0000162% In Emacs, the following two are start of buffer/end of buffer. In
163% Python they seem to be synonyms for ^$.
Fred Drake4b3f0311996-12-13 22:04:31 +0000164\item[\code{\e `}] Like \code{\^}, this only matches at the start of the
165string.
Guido van Rossum1a535601996-06-26 19:43:22 +0000166\item[\code{\e \e '}] Like \code{\$}, this only matches at the end of the
167string.
168% end of buffer
169\end{itemize}
170
171\subsection{Module Contents}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000172
173The module defines these functions, and an exception:
174
175\renewcommand{\indexsubitem}{(in module regex)}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000176
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000177\begin{funcdesc}{match}{pattern\, string}
178 Return how many characters at the beginning of \var{string} match
179 the regular expression \var{pattern}. Return \code{-1} if the
180 string does not match the pattern (this is different from a
181 zero-length match!).
182\end{funcdesc}
183
184\begin{funcdesc}{search}{pattern\, string}
185 Return the first position in \var{string} that matches the regular
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000186 expression \var{pattern}. Return \code{-1} if no position in the string
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000187 matches the pattern (this is different from a zero-length match
188 anywhere!).
189\end{funcdesc}
190
Guido van Rossum16d6e711994-08-08 12:30:22 +0000191\begin{funcdesc}{compile}{pattern\optional{\, translate}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000192 Compile a regular expression pattern into a regular expression
193 object, which can be used for matching using its \code{match} and
Guido van Rossum470be141995-03-17 16:07:09 +0000194 \code{search} methods, described below. The optional argument
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000195 \var{translate}, if present, must be a 256-character string
196 indicating how characters (both of the pattern and of the strings to
197 be matched) are translated before comparing them; the \code{i}-th
198 element of the string gives the translation for the character with
Guido van Rossum470be141995-03-17 16:07:09 +0000199 \ASCII{} code \code{i}. This can be used to implement
200 case-insensitive matching; see the \code{casefold} data item below.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000201
202 The sequence
203
204\bcode\begin{verbatim}
205prog = regex.compile(pat)
206result = prog.match(str)
207\end{verbatim}\ecode
Guido van Rossume47da0a1997-07-17 16:34:52 +0000208%
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000209is equivalent to
210
211\bcode\begin{verbatim}
212result = regex.match(pat, str)
213\end{verbatim}\ecode
Guido van Rossume47da0a1997-07-17 16:34:52 +0000214%
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000215but the version using \code{compile()} is more efficient when multiple
216regular expressions are used concurrently in a single program. (The
217compiled version of the last pattern passed to \code{regex.match()} or
218\code{regex.search()} is cached, so programs that use only a single
219regular expression at a time needn't worry about compiling regular
220expressions.)
221\end{funcdesc}
222
223\begin{funcdesc}{set_syntax}{flags}
224 Set the syntax to be used by future calls to \code{compile},
225 \code{match} and \code{search}. (Already compiled expression objects
226 are not affected.) The argument is an integer which is the OR of
227 several flag bits. The return value is the previous value of
228 the syntax flags. Names for the flags are defined in the standard
229 module \code{regex_syntax}; read the file \file{regex_syntax.py} for
230 more information.
231\end{funcdesc}
232
Barry Warsawcd77df61997-02-18 18:54:30 +0000233\begin{funcdesc}{get_syntax}{}
234 Returns the current value of the syntax flags as an integer.
235\end{funcdesc}
236
Guido van Rossum16d6e711994-08-08 12:30:22 +0000237\begin{funcdesc}{symcomp}{pattern\optional{\, translate}}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000238This is like \code{compile}, but supports symbolic group names: if a
Guido van Rossum6c4f0031995-03-07 10:14:09 +0000239parenthesis-enclosed group begins with a group name in angular
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000240brackets, e.g. \code{'\e(<id>[a-z][a-z0-9]*\e)'}, the group can
241be referenced by its name in arguments to the \code{group} method of
242the resulting compiled regular expression object, like this:
Guido van Rossum7defee71995-02-27 17:52:35 +0000243\code{p.group('id')}. Group names may contain alphanumeric characters
244and \code{'_'} only.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000245\end{funcdesc}
246
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000247\begin{excdesc}{error}
248 Exception raised when a string passed to one of the functions here
249 is not a valid regular expression (e.g., unmatched parentheses) or
250 when some other error occurs during compilation or matching. (It is
251 never an error if a string contains no match for a pattern.)
252\end{excdesc}
253
254\begin{datadesc}{casefold}
255A string suitable to pass as \var{translate} argument to
256\code{compile} to map all upper case characters to their lowercase
257equivalents.
258\end{datadesc}
259
260\noindent
261Compiled regular expression objects support these methods:
262
263\renewcommand{\indexsubitem}{(regex method)}
Guido van Rossum16d6e711994-08-08 12:30:22 +0000264\begin{funcdesc}{match}{string\optional{\, pos}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000265 Return how many characters at the beginning of \var{string} match
266 the compiled regular expression. Return \code{-1} if the string
267 does not match the pattern (this is different from a zero-length
268 match!).
269
270 The optional second parameter \var{pos} gives an index in the string
271 where the search is to start; it defaults to \code{0}. This is not
272 completely equivalent to slicing the string; the \code{'\^'} pattern
273 character matches at the real begin of the string and at positions
274 just after a newline, not necessarily at the index where the search
275 is to start.
276\end{funcdesc}
277
Guido van Rossum16d6e711994-08-08 12:30:22 +0000278\begin{funcdesc}{search}{string\optional{\, pos}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000279 Return the first position in \var{string} that matches the regular
280 expression \code{pattern}. Return \code{-1} if no position in the
281 string matches the pattern (this is different from a zero-length
282 match anywhere!).
283
284 The optional second parameter has the same meaning as for the
285 \code{match} method.
286\end{funcdesc}
287
288\begin{funcdesc}{group}{index\, index\, ...}
289This method is only valid when the last call to the \code{match}
290or \code{search} method found a match. It returns one or more
291groups of the match. If there is a single \var{index} argument,
292the result is a single string; if there are multiple arguments, the
293result is a tuple with one item per argument. If the \var{index} is
294zero, the corresponding return value is the entire matching string; if
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000295it is in the inclusive range [1..99], it is the string matching the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000296the corresponding parenthesized group (using the default syntax,
297groups are parenthesized using \code{\\(} and \code{\\)}). If no
298such group exists, the corresponding result is \code{None}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000299
300If the regular expression was compiled by \code{symcomp} instead of
301\code{compile}, the \var{index} arguments may also be strings
302identifying groups by their group name.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000303\end{funcdesc}
304
305\noindent
306Compiled regular expressions support these data attributes:
307
308\renewcommand{\indexsubitem}{(regex attribute)}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000309
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000310\begin{datadesc}{regs}
311When the last call to the \code{match} or \code{search} method found a
312match, this is a tuple of pairs of indices corresponding to the
313beginning and end of all parenthesized groups in the pattern. Indices
314are relative to the string argument passed to \code{match} or
315\code{search}. The 0-th tuple gives the beginning and end or the
316whole pattern. When the last match or search failed, this is
317\code{None}.
318\end{datadesc}
319
320\begin{datadesc}{last}
321When the last call to the \code{match} or \code{search} method found a
322match, this is the string argument passed to that method. When the
323last match or search failed, this is \code{None}.
324\end{datadesc}
325
326\begin{datadesc}{translate}
327This is the value of the \var{translate} argument to
328\code{regex.compile} that created this regular expression object. If
329the \var{translate} argument was omitted in the \code{regex.compile}
330call, this is \code{None}.
331\end{datadesc}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000332
333\begin{datadesc}{givenpat}
334The regular expression pattern as passed to \code{compile} or
335\code{symcomp}.
336\end{datadesc}
337
338\begin{datadesc}{realpat}
339The regular expression after stripping the group names for regular
340expressions compiled with \code{symcomp}. Same as \code{givenpat}
341otherwise.
342\end{datadesc}
343
344\begin{datadesc}{groupindex}
345A dictionary giving the mapping from symbolic group names to numerical
346group indices for regular expressions compiled with \code{symcomp}.
347\code{None} otherwise.
348\end{datadesc}