blob: 18b8b186759ea440cdd88cd19da0e787e65b8287 [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 Drake16f88451998-01-22 20:47:26 +000018\url{http://starship.skyport.net/crew/amk/regex/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.
Guido van Rossum1a535601996-06-26 19:43:22 +0000139%
Guido van Rossum38e0df31998-02-11 22:55:55 +0000140\fulllineitems\item[\code{\e \e 1, ... \e \e 7, \e 8, \e 9}]
Fred Drake4b3f0311996-12-13 22:04:31 +0000141Matches the contents of the group of the same
Guido van Rossum1a535601996-06-26 19:43:22 +0000142number. For example, \code{\e (.+\e ) \e \e 1} matches 'the the' or
143'55 55', but not 'the end' (note the space after the group). This
144special sequence can only be used to match one of the first 9 groups;
145groups with higher numbers can be matched using the \code{\e v}
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000146sequence. (\code{\e 8} and \code{\e 9} don't need a double backslash
Guido van Rossum38e0df31998-02-11 22:55:55 +0000147because they are not octal digits.)
Guido van Rossum1a535601996-06-26 19:43:22 +0000148%
Fred Drake4b3f0311996-12-13 22:04:31 +0000149\item[\code{\e \e b}] Matches the empty string, but only at the
Guido van Rossum1a535601996-06-26 19:43:22 +0000150beginning or end of a word. A word is defined as a sequence of
151alphanumeric characters, so the end of a word is indicated by
Fred Drake4b3f0311996-12-13 22:04:31 +0000152whitespace or a non-alphanumeric character.
Guido van Rossum1a535601996-06-26 19:43:22 +0000153%
Fred Drake4b3f0311996-12-13 22:04:31 +0000154\item[\code{\e B}] Matches the empty string, but when it is \emph{not} at the
155beginning or end of a word.
Guido van Rossum1a535601996-06-26 19:43:22 +0000156%
Fred Drake4b3f0311996-12-13 22:04:31 +0000157\item[\code{\e v}] Must be followed by a two digit decimal number, and
Fred Drake054f8fd1998-01-12 18:28:20 +0000158matches the contents of the group of the same number. The group
159number must be between 1 and 99, inclusive.
Guido van Rossum1a535601996-06-26 19:43:22 +0000160%
161\item[\code{\e w}]Matches any alphanumeric character; this is
162equivalent to the set \code{[a-zA-Z0-9]}.
163%
Fred Drake4b3f0311996-12-13 22:04:31 +0000164\item[\code{\e W}] Matches any non-alphanumeric character; this is
165equivalent to the set \code{[\^a-zA-Z0-9]}.
166\item[\code{\e <}] Matches the empty string, but only at the beginning of a
Guido van Rossum1a535601996-06-26 19:43:22 +0000167word. A word is defined as a sequence of alphanumeric characters, so
168the end of a word is indicated by whitespace or a non-alphanumeric
Fred Drake4b3f0311996-12-13 22:04:31 +0000169character.
170\item[\code{\e >}] Matches the empty string, but only at the end of a
171word.
Guido van Rossum1a535601996-06-26 19:43:22 +0000172
Fred Drake4b3f0311996-12-13 22:04:31 +0000173\item[\code{\e \e \e \e}] Matches a literal backslash.
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000174
Guido van Rossum1a535601996-06-26 19:43:22 +0000175% In Emacs, the following two are start of buffer/end of buffer. In
176% Python they seem to be synonyms for ^$.
Fred Drake4b3f0311996-12-13 22:04:31 +0000177\item[\code{\e `}] Like \code{\^}, this only matches at the start of the
178string.
Fred Drake054f8fd1998-01-12 18:28:20 +0000179\item[\code{\e \e '}] Like \code{\$}, this only matches at the end of
180the string.
Guido van Rossum1a535601996-06-26 19:43:22 +0000181% end of buffer
182\end{itemize}
183
184\subsection{Module Contents}
Guido van Rossum38e0df31998-02-11 22:55:55 +0000185\nodename{Contents of Module regex}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000186
187The module defines these functions, and an exception:
188
Fred Drake19479911998-02-13 06:58:54 +0000189\setindexsubitem{(in module regex)}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000190
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000191\begin{funcdesc}{match}{pattern\, string}
192 Return how many characters at the beginning of \var{string} match
193 the regular expression \var{pattern}. Return \code{-1} if the
194 string does not match the pattern (this is different from a
195 zero-length match!).
196\end{funcdesc}
197
198\begin{funcdesc}{search}{pattern\, string}
199 Return the first position in \var{string} that matches the regular
Guido van Rossum6240b0b1996-10-24 22:49:13 +0000200 expression \var{pattern}. Return \code{-1} if no position in the string
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000201 matches the pattern (this is different from a zero-length match
202 anywhere!).
203\end{funcdesc}
204
Guido van Rossum16d6e711994-08-08 12:30:22 +0000205\begin{funcdesc}{compile}{pattern\optional{\, translate}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000206 Compile a regular expression pattern into a regular expression
Fred Drake054f8fd1998-01-12 18:28:20 +0000207 object, which can be used for matching using its \code{match()} and
208 \code{search()} methods, described below. The optional argument
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000209 \var{translate}, if present, must be a 256-character string
210 indicating how characters (both of the pattern and of the strings to
Fred Drake054f8fd1998-01-12 18:28:20 +0000211 be matched) are translated before comparing them; the \var{i}-th
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000212 element of the string gives the translation for the character with
Fred Drake054f8fd1998-01-12 18:28:20 +0000213 \ASCII{} code \var{i}. This can be used to implement
Guido van Rossum470be141995-03-17 16:07:09 +0000214 case-insensitive matching; see the \code{casefold} data item below.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000215
216 The sequence
217
Fred Drake19479911998-02-13 06:58:54 +0000218\begin{verbatim}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000219prog = regex.compile(pat)
220result = prog.match(str)
Fred Drake19479911998-02-13 06:58:54 +0000221\end{verbatim}
Guido van Rossume47da0a1997-07-17 16:34:52 +0000222%
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000223is equivalent to
224
Fred Drake19479911998-02-13 06:58:54 +0000225\begin{verbatim}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000226result = regex.match(pat, str)
Fred Drake19479911998-02-13 06:58:54 +0000227\end{verbatim}
Fred Drake054f8fd1998-01-12 18:28:20 +0000228
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000229but the version using \code{compile()} is more efficient when multiple
230regular expressions are used concurrently in a single program. (The
231compiled version of the last pattern passed to \code{regex.match()} or
232\code{regex.search()} is cached, so programs that use only a single
233regular expression at a time needn't worry about compiling regular
234expressions.)
235\end{funcdesc}
236
237\begin{funcdesc}{set_syntax}{flags}
Fred Drake054f8fd1998-01-12 18:28:20 +0000238 Set the syntax to be used by future calls to \code{compile()},
239 \code{match()} and \code{search()}. (Already compiled expression
240 objects are not affected.) The argument is an integer which is the
241 OR of several flag bits. The return value is the previous value of
242 the syntax flags. Names for the flags are defined in the standard
243 module \code{regex_syntax}\refstmodindex{regex_syntax}; read the
244 file \file{regex_syntax.py} for more information.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000245\end{funcdesc}
246
Barry Warsawcd77df61997-02-18 18:54:30 +0000247\begin{funcdesc}{get_syntax}{}
248 Returns the current value of the syntax flags as an integer.
249\end{funcdesc}
250
Guido van Rossum16d6e711994-08-08 12:30:22 +0000251\begin{funcdesc}{symcomp}{pattern\optional{\, translate}}
Fred Drake054f8fd1998-01-12 18:28:20 +0000252This is like \code{compile()}, but supports symbolic group names: if a
Guido van Rossum6c4f0031995-03-07 10:14:09 +0000253parenthesis-enclosed group begins with a group name in angular
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000254brackets, e.g. \code{'\e(<id>[a-z][a-z0-9]*\e)'}, the group can
Fred Drake054f8fd1998-01-12 18:28:20 +0000255be referenced by its name in arguments to the \code{group()} method of
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000256the resulting compiled regular expression object, like this:
Guido van Rossum7defee71995-02-27 17:52:35 +0000257\code{p.group('id')}. Group names may contain alphanumeric characters
258and \code{'_'} only.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000259\end{funcdesc}
260
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000261\begin{excdesc}{error}
262 Exception raised when a string passed to one of the functions here
263 is not a valid regular expression (e.g., unmatched parentheses) or
264 when some other error occurs during compilation or matching. (It is
265 never an error if a string contains no match for a pattern.)
266\end{excdesc}
267
268\begin{datadesc}{casefold}
Fred Drake054f8fd1998-01-12 18:28:20 +0000269A string suitable to pass as the \var{translate} argument to
270\code{compile()} to map all upper case characters to their lowercase
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000271equivalents.
272\end{datadesc}
273
274\noindent
275Compiled regular expression objects support these methods:
276
Fred Drake19479911998-02-13 06:58:54 +0000277\setindexsubitem{(regex method)}
Guido van Rossum16d6e711994-08-08 12:30:22 +0000278\begin{funcdesc}{match}{string\optional{\, pos}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000279 Return how many characters at the beginning of \var{string} match
280 the compiled regular expression. Return \code{-1} if the string
281 does not match the pattern (this is different from a zero-length
282 match!).
283
Fred Drake054f8fd1998-01-12 18:28:20 +0000284 The optional second parameter, \var{pos}, gives an index in the string
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000285 where the search is to start; it defaults to \code{0}. This is not
286 completely equivalent to slicing the string; the \code{'\^'} pattern
287 character matches at the real begin of the string and at positions
288 just after a newline, not necessarily at the index where the search
289 is to start.
290\end{funcdesc}
291
Guido van Rossum16d6e711994-08-08 12:30:22 +0000292\begin{funcdesc}{search}{string\optional{\, pos}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000293 Return the first position in \var{string} that matches the regular
294 expression \code{pattern}. Return \code{-1} if no position in the
295 string matches the pattern (this is different from a zero-length
296 match anywhere!).
297
298 The optional second parameter has the same meaning as for the
Fred Drake054f8fd1998-01-12 18:28:20 +0000299 \code{match()} method.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000300\end{funcdesc}
301
302\begin{funcdesc}{group}{index\, index\, ...}
Fred Drake054f8fd1998-01-12 18:28:20 +0000303This method is only valid when the last call to the \code{match()}
304or \code{search()} method found a match. It returns one or more
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000305groups of the match. If there is a single \var{index} argument,
306the result is a single string; if there are multiple arguments, the
307result is a tuple with one item per argument. If the \var{index} is
308zero, the corresponding return value is the entire matching string; if
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000309it is in the inclusive range [1..99], it is the string matching the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000310the corresponding parenthesized group (using the default syntax,
Fred Drake875c8071998-01-02 02:50:13 +0000311groups are parenthesized using \code{{\e}(} and \code{{\e})}). If no
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000312such group exists, the corresponding result is \code{None}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000313
Fred Drake054f8fd1998-01-12 18:28:20 +0000314If the regular expression was compiled by \code{symcomp()} instead of
315\code{compile()}, the \var{index} arguments may also be strings
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000316identifying groups by their group name.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000317\end{funcdesc}
318
319\noindent
320Compiled regular expressions support these data attributes:
321
Fred Drake19479911998-02-13 06:58:54 +0000322\setindexsubitem{(regex attribute)}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000323
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000324\begin{datadesc}{regs}
Fred Drake054f8fd1998-01-12 18:28:20 +0000325When the last call to the \code{match()} or \code{search()} method found a
326match, this is a tuple of pairs of indexes corresponding to the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000327beginning and end of all parenthesized groups in the pattern. Indices
Fred Drake054f8fd1998-01-12 18:28:20 +0000328are relative to the string argument passed to \code{match()} or
329\code{search()}. The 0-th tuple gives the beginning and end or the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000330whole pattern. When the last match or search failed, this is
331\code{None}.
332\end{datadesc}
333
334\begin{datadesc}{last}
Fred Drake054f8fd1998-01-12 18:28:20 +0000335When the last call to the \code{match()} or \code{search()} method found a
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000336match, this is the string argument passed to that method. When the
337last match or search failed, this is \code{None}.
338\end{datadesc}
339
340\begin{datadesc}{translate}
341This is the value of the \var{translate} argument to
Fred Drake054f8fd1998-01-12 18:28:20 +0000342\code{regex.compile()} that created this regular expression object. If
343the \var{translate} argument was omitted in the \code{regex.compile()}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000344call, this is \code{None}.
345\end{datadesc}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000346
347\begin{datadesc}{givenpat}
Fred Drake054f8fd1998-01-12 18:28:20 +0000348The regular expression pattern as passed to \code{compile()} or
349\code{symcomp()}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000350\end{datadesc}
351
352\begin{datadesc}{realpat}
353The regular expression after stripping the group names for regular
Fred Drake054f8fd1998-01-12 18:28:20 +0000354expressions compiled with \code{symcomp()}. Same as \code{givenpat}
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000355otherwise.
356\end{datadesc}
357
358\begin{datadesc}{groupindex}
359A dictionary giving the mapping from symbolic group names to numerical
Fred Drake054f8fd1998-01-12 18:28:20 +0000360group indexes for regular expressions compiled with \code{symcomp()}.
Guido van Rossum326c0bc1994-01-03 00:00:31 +0000361\code{None} otherwise.
362\end{datadesc}