blob: f9f4871e6195e41379e4a2402a82bdab21b70629 [file] [log] [blame]
Guido van Rossum1acceb01997-08-14 23:12:18 +00001\section{Built-in Module \sectcode{re}}
2\label{module-re}
3
4\bimodindex{re}
5
6% XXX Remove before 1.5final release.
Guido van Rossume4eb2231997-12-17 00:23:39 +00007{\large\bf This documentation is preliminary and incomplete. If you
Guido van Rossum1acceb01997-08-14 23:12:18 +00008find a bug or documentation error, or just find something unclear,
9please send a message to
10\code{string-sig@python.org}, and we'll fix it.}
11
12This module provides regular expression matching operations similar to
Guido van Rossum0b334101997-12-08 17:33:40 +000013those found in Perl. It's 8-bit clean: both patterns and strings may
14contain null bytes and characters whose high bit is set. It is always
15available.
Guido van Rossum1acceb01997-08-14 23:12:18 +000016
17Regular expressions use the backslash character (\code{\e}) to
18indicate special forms or to allow special characters to be used
19without invoking their special meaning. This collides with Python's
20usage of the same character for the same purpose in string literals;
21for example, to match a literal backslash, one might have to write
Guido van Rossum0b334101997-12-08 17:33:40 +000022\code{\e\e\e\e} as the pattern string, because the regular expression
23must be \code{\e\e}, and each backslash must be expressed as
24\code{\e\e} inside a regular Python string literal.
Guido van Rossum1acceb01997-08-14 23:12:18 +000025
26The solution is to use Python's raw string notation for regular
27expression patterns; backslashes are not handled in any special way in
28a string literal prefixed with 'r'. So \code{r"\e n"} is a two
29character string containing a backslash and the letter 'n', while
30\code{"\e n"} is a one-character string containing a newline. Usually
31patterns will be expressed in Python code using this raw string notation.
32
33% XXX Can the following section be dropped, or should it be boiled down?
34
35%\strong{Please note:} There is a little-known fact about Python string
36%literals which means that you don't usually have to worry about
37%doubling backslashes, even though they are used to escape special
38%characters in string literals as well as in regular expressions. This
39%is because Python doesn't remove backslashes from string literals if
40%they are followed by an unrecognized escape character.
41%\emph{However}, if you want to include a literal \dfn{backslash} in a
42%regular expression represented as a string literal, you have to
43%\emph{quadruple} it or enclose it in a singleton character class.
44%E.g.\ to extract \LaTeX\ \code{\e section\{{\rm
45%\ldots}\}} headers from a document, you can use this pattern:
46%\code{'[\e ] section\{\e (.*\e )\}'}. \emph{Another exception:}
47%the escape sequence \code{\e b} is significant in string literals
48%(where it means the ASCII bell character) as well as in Emacs regular
49%expressions (where it stands for a word boundary), so in order to
50%search for a word boundary, you should use the pattern \code{'\e \e b'}.
51%Similarly, a backslash followed by a digit 0-7 should be doubled to
52%avoid interpretation as an octal escape.
53
Guido van Rossum48d04371997-12-11 20:19:08 +000054\subsection{Regular Expression Syntax}
Guido van Rossum1acceb01997-08-14 23:12:18 +000055
56A regular expression (or RE) specifies a set of strings that matches
57it; the functions in this module let you check if a particular string
58matches a given regular expression (or if a given regular expression
59matches a particular string, which comes down to the same thing).
60
61Regular expressions can be concatenated to form new regular
62expressions; if \emph{A} and \emph{B} are both regular expressions,
63then \emph{AB} is also an regular expression. If a string \emph{p}
64matches A and another string \emph{q} matches B, the string \emph{pq}
65will match AB. Thus, complex expressions can easily be constructed
66from simpler primitive expressions like the ones described here. For
67details of the theory and implementation of regular expressions,
68consult the Friedl book referenced below, or almost any textbook about
69compiler construction.
70
Guido van Rossum0b334101997-12-08 17:33:40 +000071A brief explanation of the format of regular expressions follows.
72%For further information and a gentler presentation, consult XXX somewhere.
Guido van Rossum1acceb01997-08-14 23:12:18 +000073
74Regular expressions can contain both special and ordinary characters.
75Most ordinary characters, like '\code{A}', '\code{a}', or '\code{0}',
76are the simplest regular expressions; they simply match themselves.
77You can concatenate ordinary characters, so '\code{last}' matches the
78characters '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'.)
81
82Some characters, like \code{|} or \code{(}, are special. Special
83characters either stand for classes of ordinary characters, or affect
84how the regular expressions around them are interpreted.
85
86The special characters are:
87\begin{itemize}
88\item[\code{.}] (Dot.) In the default mode, this matches any
89character except a newline. If the \code{DOTALL} flag has been
90specified, this matches any character including a newline.
91\item[\code{\^}] (Caret.) Matches the start of the string, and in
92\code{MULTILINE} mode also immediately after each newline.
Guido van Rossum48d04371997-12-11 20:19:08 +000093\item[\code{\$}] Matches the end of the string, and in
94\code{MULTILINE} mode also matches before a newline.
Guido van Rossum1acceb01997-08-14 23:12:18 +000095\code{foo} matches both 'foo' and 'foobar', while the regular
Guido van Rossum48d04371997-12-11 20:19:08 +000096expression \code{foo\$} matches only 'foo'.
Guido van Rossum1acceb01997-08-14 23:12:18 +000097%
98\item[\code{*}] Causes the resulting RE to
99match 0 or more repetitions of the preceding RE, as many repetitions
100as are possible. \code{ab*} will
101match 'a', 'ab', or 'a' followed by any number of 'b's.
102%
103\item[\code{+}] Causes the
104resulting RE to match 1 or more repetitions of the preceding RE.
105\code{ab+} will match 'a' followed by any non-zero number of 'b's; it
106will not match just 'a'.
107%
108\item[\code{?}] Causes the resulting RE to
109match 0 or 1 repetitions of the preceding RE. \code{ab?} will
110match either 'a' or 'ab'.
111\item[\code{*?}, \code{+?}, \code{??}] The \code{*}, \code{+}, and
112\code{?} qualifiers are all \dfn{greedy}; they match as much text as
113possible. Sometimes this behaviour isn't desired; if the RE
114\code{<.*>} is matched against \code{<H1>title</H1>}, it will match the
115entire string, and not just \code{<H1>}.
116Adding \code{?} after the qualifier makes it perform the match in
117\dfn{non-greedy} or \dfn{minimal} fashion; as few characters as
118possible will be matched. Using \code{.*?} in the previous
Guido van Rossum0b334101997-12-08 17:33:40 +0000119expression will match only \code{<H1>}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000120%
Guido van Rossum0148bbf1997-12-22 22:41:40 +0000121\item[\code{\{\var{m},\var{n}\}}] Causes the resulting RE to match from
122\var{m} to \var{n} repetitions of the preceding RE, attempting to
123match as many repetitions as possible. For example, \code{a\{3,5\}}
124will match from 3 to 5 'a' characters.
125%
126\item[\code{\{\var{m},\var{n}\}?}] Causes the resulting RE to
127match from \var{m} to \var{n} repetitions of the preceding RE,
128attempting to match as \emph{few} repetitions as possible. This is
129the non-greedy version of the previous qualifier. For example, on the
1306-character string 'aaaaaa', \code{a\{3,5\}} will match 5 'a'
131characters, while \code{a\{3,5\}?} will only match 3 characters.
132%
Guido van Rossum1acceb01997-08-14 23:12:18 +0000133\item[\code{\e}] Either escapes special characters (permitting you to match
134characters like '*?+\&\$'), or signals a special sequence; special
135sequences are discussed below.
136
137If you're not using a raw string to
138express the pattern, remember that Python also uses the
139backslash as an escape sequence in string literals; if the escape
140sequence isn't recognized by Python's parser, the backslash and
141subsequent character are included in the resulting string. However,
142if Python would recognize the resulting sequence, the backslash should
143be repeated twice. This is complicated and hard to understand, so
Guido van Rossum48d04371997-12-11 20:19:08 +0000144it's highly recommended that you use raw strings for all but the simplest expressions.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000145%
146\item[\code{[]}] Used to indicate a set of characters. Characters can
Guido van Rossum48d04371997-12-11 20:19:08 +0000147be listed individually, or a range of characters can be indicated by
148giving two characters and separating them by a '-'. Special
149characters are not active inside sets. For example, \code{[akm\$]}
150will match any of the characters 'a', 'k', 'm', or '\$'; \code{[a-z]}
151will match any lowercase letter and \code{[a-zA-Z0-9]} matches any
152letter or digit. Character classes such as \code{\e w} or \code {\e
153S} (defined below) are also acceptable inside a range. If you want to
154include a \code{]} or a \code{-} inside a set, precede it with a
155backslash.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000156
157Characters \emph{not} within a range can be matched by including a
158\code{\^} as the first character of the set; \code{\^} elsewhere will
159simply match the '\code{\^}' character.
160%
161\item[\code{|}]\code{A|B}, where A and B can be arbitrary REs,
162creates a regular expression that will match either A or B. This can
163be used inside groups (see below) as well. To match a literal '|',
164use \code{\e|}, or enclose it inside a character class, like \code{[|]}.
165%
Guido van Rossum48d04371997-12-11 20:19:08 +0000166\item[\code{(...)}] Matches whatever regular expression is inside the
167parentheses, and indicates the start and end of a group; the contents
168of a group can be retrieved after a match has been performed, and can
169be matched later in the string with the \code{\e \var{number}} special
170sequence, described below. To match the literals '(' or ')',
Guido van Rossum1acceb01997-08-14 23:12:18 +0000171use \code{\e(} or \code{\e)}, or enclose them inside a character
172class: \code{[(] [)]}.
173%
Guido van Rossum0b334101997-12-08 17:33:40 +0000174\item[\code{(?...)}] This is an extension notation (a '?' following a
175'(' is not meaningful otherwise). The first character after the '?'
176determines what the meaning and further syntax of the construct is.
177Following are the currently supported extensions.
178%
Guido van Rossumbd49ac41997-12-10 23:05:53 +0000179\item[\code{(?iLmsx)}] (One or more letters from the set 'i', 'L', 'm', 's',
Guido van Rossum0b334101997-12-08 17:33:40 +0000180'x'.) The group matches the empty string; the letters set the
181corresponding flags (re.I, re.L, re.M, re.S, re.X) for the entire regular
Guido van Rossum48d04371997-12-11 20:19:08 +0000182expression. This is useful if you wish include the flags as part of
183the regular expression, instead of passing a \var{flag} argument to
184the \code{compile} function.
Guido van Rossum0b334101997-12-08 17:33:40 +0000185%
Guido van Rossum1acceb01997-08-14 23:12:18 +0000186\item[\code{(?:...)}] A non-grouping version of regular parentheses.
187Matches whatever's inside the parentheses, but the text matched by the
188group \emph{cannot} be retrieved after performing a match or
189referenced later in the pattern.
190%
191\item[\code{(?P<\var{name}>...)}] Similar to regular parentheses, but
192the text matched by the group is accessible via the symbolic group
193name \var{name}. Group names must be valid Python identifiers. A
194symbolic group is also a numbered group, just as if the group were not
195named. So the group named 'id' in the example above can also be
196referenced as the numbered group 1.
197
Guido van Rossum48d04371997-12-11 20:19:08 +0000198For example, if the pattern is
199\code{(?P<id>[a-zA-Z_]\e w*)}, the group can be referenced by its
Guido van Rossum1acceb01997-08-14 23:12:18 +0000200name in arguments to methods of match objects, such as \code{m.group('id')}
201or \code{m.end('id')}, and also by name in pattern text (e.g. \code{(?P=id)}) and
202replacement text (e.g. \code{\e g<id>}).
203%
Guido van Rossum48d04371997-12-11 20:19:08 +0000204\item[\code{(?P=\var{name})}] Matches whatever text was matched by the earlier group named \var{name}.
205%
Guido van Rossum1acceb01997-08-14 23:12:18 +0000206\item[\code{(?\#...)}] A comment; the contents of the parentheses are simply ignored.
207%
Guido van Rossum0b334101997-12-08 17:33:40 +0000208\item[\code{(?=...)}] Matches if \code{...} matches next, but doesn't consume any of the string. This is called a lookahead assertion. For example,
209\code{Isaac (?=Asimov)} will match 'Isaac~' only if it's followed by 'Asimov'.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000210%
Guido van Rossum0b334101997-12-08 17:33:40 +0000211\item[\code{(?!...)}] Matches if \code{...} doesn't match next. This is a negative lookahead assertion. For example,
212For example,
213\code{Isaac (?!Asimov)} will match 'Isaac~' only if it's \emph{not} followed by 'Asimov'.
214
Guido van Rossum1acceb01997-08-14 23:12:18 +0000215\end{itemize}
216
217The special sequences consist of '\code{\e}' and a character from the
218list below. If the ordinary character is not on the list, then the
219resulting RE will match the second character. For example,
Guido van Rossum48d04371997-12-11 20:19:08 +0000220\code{\e\$} matches the character '\$'.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000221
222\begin{itemize}
223
224%
225\item[\code{\e \var{number}}] Matches the contents of the group of the
Guido van Rossum0b334101997-12-08 17:33:40 +0000226same number. Groups are numbered starting from 1. For example,
227\code{(.+) \e 1} matches 'the the' or '55 55', but not 'the end' (note
228the space after the group). This special sequence can only be used to
229match one of the first 99 groups. If the first digit of \var{number}
230is 0, or \var{number} is 3 octal digits long, it will not be interpreted
231as a group match, but as the character with octal value \var{number}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000232%
233\item[\code{\e A}] Matches only at the start of the string.
234%
235\item[\code{\e b}] Matches the empty string, but only at the
236beginning or end of a word. A word is defined as a sequence of
237alphanumeric characters, so the end of a word is indicated by
Guido van Rossum48d04371997-12-11 20:19:08 +0000238whitespace or a non-alphanumeric character. Inside a character range,
239\code{\e b} represents the backspace character, for compatibility with
240Python's string literals.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000241%
Guido van Rossum0b334101997-12-08 17:33:40 +0000242\item[\code{\e B}] Matches the empty string, but only when it is
243\emph{not} at the beginning or end of a word.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000244%
245\item[\code{\e d}]Matches any decimal digit; this is
246equivalent to the set \code{[0-9]}.
247%
248\item[\code{\e D}]Matches any non-digit character; this is
Guido van Rossumd7dc2eb1997-10-22 03:03:44 +0000249equivalent to the set \code{[{\^}0-9]}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000250%
251\item[\code{\e s}]Matches any whitespace character; this is
252equivalent to the set \code{[ \e t\e n\e r\e f\e v]}.
253%
254\item[\code{\e S}]Matches any non-whitespace character; this is
Guido van Rossumd7dc2eb1997-10-22 03:03:44 +0000255equivalent to the set \code{[{\^} \e t\e n\e r\e f\e v]}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000256%
Guido van Rossum0b334101997-12-08 17:33:40 +0000257\item[\code{\e w}]When the LOCALE flag is not specified, matches any alphanumeric character; this is
258equivalent to the set \code{[a-zA-Z0-9_]}. With LOCALE, it will match
259the set \code{[0-9_]} plus whatever characters are defined as letters
260for the current locale.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000261%
Guido van Rossum0b334101997-12-08 17:33:40 +0000262\item[\code{\e W}]When the LOCALE flag is not specified, matches any
263non-alphanumeric character; this is equivalent to the set
264\code{[{\^}a-zA-Z0-9_]}. With LOCALE, it will match any character
265not in the set \code{[0-9_]}, and not defined as a letter
266for the current locale.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000267
268\item[\code{\e Z}]Matches only at the end of the string.
269%
270
271\item[\code{\e \e}] Matches a literal backslash.
272
273\end{itemize}
274
275\subsection{Module Contents}
276
277The module defines the following functions and constants, and an exception:
278
279\renewcommand{\indexsubitem}{(in module re)}
280
281\begin{funcdesc}{compile}{pattern\optional{\, flags}}
282 Compile a regular expression pattern into a regular expression
283 object, which can be used for matching using its \code{match} and
284 \code{search} methods, described below.
285
Guido van Rossum0b334101997-12-08 17:33:40 +0000286 The expression's behaviour can be modified by specifying a
287 \var{flags} value. Values can be any of the following variables,
288 combined using bitwise OR (the \code{|} operator).
289
Guido van Rossuma42c1781997-12-09 20:41:47 +0000290\begin{itemize}
Guido van Rossum0b334101997-12-08 17:33:40 +0000291
Guido van Rossum48d04371997-12-11 20:19:08 +0000292\item {I or IGNORECASE or \code{(?i)}}
Guido van Rossum0b334101997-12-08 17:33:40 +0000293
Guido van Rossum48d04371997-12-11 20:19:08 +0000294{Perform case-insensitive matching; expressions like \code{[A-Z]} will match
295lowercase letters, too. This is not affected by the current locale.
296}
297\item {L or LOCALE or \code{(?L)}}
Guido van Rossum0b334101997-12-08 17:33:40 +0000298
Guido van Rossum48d04371997-12-11 20:19:08 +0000299{Make \code{\e w}, \code{\e W}, \code{\e b},
300\code{\e B}, dependent on the current locale.
301}
Guido van Rossuma42c1781997-12-09 20:41:47 +0000302
Guido van Rossum48d04371997-12-11 20:19:08 +0000303\item {M or MULTILINE or \code{(?m)}}
304
305{When specified, the pattern character \code{\^} matches at the
306 beginning of the string and at the beginning of each line
307 (immediately following each newline); and the pattern character
308\code{\$} matches at the end of the string and at the end of each line
309(immediately preceding each newline).
Guido van Rossum0b334101997-12-08 17:33:40 +0000310By default, \code{\^} matches only at the beginning of the string, and
311\code{\$} only at the end of the string and immediately before the
312newline (if any) at the end of the string.
Guido van Rossum48d04371997-12-11 20:19:08 +0000313}
Guido van Rossum0b334101997-12-08 17:33:40 +0000314
Guido van Rossum48d04371997-12-11 20:19:08 +0000315\item {S or DOTALL or \code{(?s)}}
Guido van Rossum0b334101997-12-08 17:33:40 +0000316
Guido van Rossum48d04371997-12-11 20:19:08 +0000317{Make the \code{.} special character any character at all, including a
318newline; without this flag, \code{.} will match anything \emph{except}
319a newline.}
320
321\item {X or VERBOSE or \code{(?x)}}
322
323{Ignore whitespace within the pattern
324except when in a character class or preceded by an unescaped
325backslash, and, when a line contains a \code{\#} neither in a character
326class or preceded by an unescaped backslash, all characters from the
327leftmost such \code{\#} through the end of the line are ignored. }
Guido van Rossum0b334101997-12-08 17:33:40 +0000328
Guido van Rossuma42c1781997-12-09 20:41:47 +0000329\end{itemize}
Guido van Rossum0b334101997-12-08 17:33:40 +0000330
Guido van Rossum1acceb01997-08-14 23:12:18 +0000331 The sequence
332%
333\bcode\begin{verbatim}
334prog = re.compile(pat)
335result = prog.match(str)
336\end{verbatim}\ecode
337%
338is equivalent to
339%
340\bcode\begin{verbatim}
341result = re.match(pat, str)
342\end{verbatim}\ecode
343%
Guido van Rossum48d04371997-12-11 20:19:08 +0000344but the version using \code{compile()} is more efficient when the
345expression will be used several times in a single program.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000346%(The compiled version of the last pattern passed to \code{regex.match()} or
347%\code{regex.search()} is cached, so programs that use only a single
348%regular expression at a time needn't worry about compiling regular
349%expressions.)
350\end{funcdesc}
351
352\begin{funcdesc}{escape}{string}
Guido van Rossum48d04371997-12-11 20:19:08 +0000353 Return \var{string} with all non-alphanumerics backslashed; this is
354 useful if you want to match an arbitrary literal string that may have
355 regular expression metacharacters in it.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000356\end{funcdesc}
357
358\begin{funcdesc}{match}{pattern\, string\optional{\, flags}}
359 If zero or more characters at the beginning of \var{string} match
360 the regular expression \var{pattern}, return a corresponding
Guido van Rossum0148bbf1997-12-22 22:41:40 +0000361 \code{MatchObject} instance. Return \code{None} if the string does not
Guido van Rossum1acceb01997-08-14 23:12:18 +0000362 match the pattern; note that this is different from a zero-length
363 match.
364\end{funcdesc}
365
366\begin{funcdesc}{search}{pattern\, string\optional{\, flags}}
367 Scan through \var{string} looking for a location where the regular
Guido van Rossum0148bbf1997-12-22 22:41:40 +0000368 expression \var{pattern} produces a match, and return a corresponding \code{MatchObject} instance.
369 Return \code{None} if no
Guido van Rossum1acceb01997-08-14 23:12:18 +0000370 position in the string matches the pattern; note that this is
371 different from finding a zero-length match at some point in the string.
372\end{funcdesc}
373
374\begin{funcdesc}{split}{pattern\, string\, \optional{, maxsplit=0}}
375 Split \var{string} by the occurrences of \var{pattern}. If
376 capturing parentheses are used in pattern, then occurrences of
377 patterns or subpatterns are also returned.
378%
379\bcode\begin{verbatim}
380>>> re.split('[\W]+', 'Words, words, words.')
381['Words', 'words', 'words', '']
382>>> re.split('([\W]+)', 'Words, words, words.')
383['Words', ', ', 'words', ', ', 'words', '.', '']
384\end{verbatim}\ecode
385%
386 This function combines and extends the functionality of
Guido van Rossum0b334101997-12-08 17:33:40 +0000387 the old \code{regex.split()} and \code{regex.splitx()}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000388\end{funcdesc}
389
390\begin{funcdesc}{sub}{pattern\, repl\, string\optional{, count=0}}
391Return the string obtained by replacing the leftmost non-overlapping
392occurrences of \var{pattern} in \var{string} by the replacement
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000393\var{repl}. If the pattern isn't found, \var{string} is returned
394unchanged. \var{repl} can be a string or a function; if a function,
395it is called for every non-overlapping occurance of \var{pattern}.
Guido van Rossum0b334101997-12-08 17:33:40 +0000396The function takes a single match object argument, and returns the
397replacement string. For example:
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000398%
399\bcode\begin{verbatim}
400>>> def dashrepl(matchobj):
401... if matchobj.group(0) == '-': return ' '
402... else: return '-'
403>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
404'pro--gram files'
405\end{verbatim}\ecode
406%
Guido van Rossum0b334101997-12-08 17:33:40 +0000407The pattern may be a string or a
Guido van Rossum48d04371997-12-11 20:19:08 +0000408regex object; if you need to specify
409regular expression flags, you must use a regex object, or use
410embedded modifiers in a pattern; e.g.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000411%
412\bcode\begin{verbatim}
413sub("(?i)b+", "x", "bbbb BBBB") returns 'x x'.
414\end{verbatim}\ecode
415%
416The optional argument \var{count} is the maximum number of pattern
417occurrences to be replaced; count must be a non-negative integer, and
418the default value of 0 means to replace all occurrences.
419
420Empty matches for the pattern are replaced only when not adjacent to a
421previous match, so \code{sub('x*', '-', 'abc')} returns '-a-b-c-'.
422\end{funcdesc}
423
424\begin{funcdesc}{subn}{pattern\, repl\, string\optional{, count=0}}
425Perform the same operation as \code{sub()}, but return a tuple
426\code{(new_string, number_of_subs_made)}.
427\end{funcdesc}
428
429\begin{excdesc}{error}
430 Exception raised when a string passed to one of the functions here
431 is not a valid regular expression (e.g., unmatched parentheses) or
432 when some other error occurs during compilation or matching. (It is
433 never an error if a string contains no match for a pattern.)
434\end{excdesc}
435
436\subsection{Regular Expression Objects}
437Compiled regular expression objects support the following methods and
438attributes:
439
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000440\renewcommand{\indexsubitem}{(re method)}
Guido van Rossum0b334101997-12-08 17:33:40 +0000441\begin{funcdesc}{match}{string\optional{\, pos}\optional{\, endpos}}
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000442 If zero or more characters at the beginning of \var{string} match
443 this regular expression, return a corresponding
Guido van Rossum48d04371997-12-11 20:19:08 +0000444 \code{MatchObject} instance. Return \code{None} if the string does not
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000445 match the pattern; note that this is different from a zero-length
446 match.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000447
448 The optional second parameter \var{pos} gives an index in the string
Guido van Rossum48d04371997-12-11 20:19:08 +0000449 where the search is to start; it defaults to \code{0}. The
450 \code{'\^'} pattern character will match at the index where the
451 search is to start.
Guido van Rossum0b334101997-12-08 17:33:40 +0000452
453 The optional parameter \var{endpos} limits how far the string will
454 be searched; it will be as if the string is \var{endpos} characters
455 long, so only the characters from \var{pos} to \var{endpos} will be
456 searched for a match.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000457\end{funcdesc}
458
Guido van Rossum0b334101997-12-08 17:33:40 +0000459\begin{funcdesc}{search}{string\optional{\, pos}\optional{\, endpos}}
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000460 Scan through \var{string} looking for a location where this regular
461 expression produces a match. Return \code{None} if no
462 position in the string matches the pattern; note that this is
463 different from finding a zero-length match at some point in the string.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000464
Guido van Rossum48d04371997-12-11 20:19:08 +0000465 The optional \var{pos} and \var{endpos} parameters have the same
466 meaning as for the \code{match} method.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000467\end{funcdesc}
468
469\begin{funcdesc}{split}{string\, \optional{, maxsplit=0}}
470Identical to the \code{split} function, using the compiled pattern.
471\end{funcdesc}
472
473\begin{funcdesc}{sub}{repl\, string\optional{, count=0}}
474Identical to the \code{sub} function, using the compiled pattern.
475\end{funcdesc}
476
477\begin{funcdesc}{subn}{repl\, string\optional{, count=0}}
478Identical to the \code{subn} function, using the compiled pattern.
479\end{funcdesc}
480
481\renewcommand{\indexsubitem}{(regex attribute)}
482
483\begin{datadesc}{flags}
484The flags argument used when the regex object was compiled, or 0 if no
485flags were provided.
486\end{datadesc}
487
488\begin{datadesc}{groupindex}
489A dictionary mapping any symbolic group names (defined by
490\code{?P<\var{id}>}) to group numbers. The dictionary is empty if no
491symbolic groups were used in the pattern.
492\end{datadesc}
493
494\begin{datadesc}{pattern}
495The pattern string from which the regex object was compiled.
496\end{datadesc}
497
Guido van Rossum48d04371997-12-11 20:19:08 +0000498\subsection{MatchObjects}
499\code{Matchobject} instances support the following methods and attributes:
Guido van Rossum1acceb01997-08-14 23:12:18 +0000500
Guido van Rossum48d04371997-12-11 20:19:08 +0000501\begin{funcdesc}{group}{\optional{g1, g2, ...}}
502Returns one or more groups of the match. If there is a single
503\var{index} argument, the result is a single string; if there are
504multiple arguments, the result is a tuple with one item per argument.
505If the \var{index} is zero, the corresponding return value is the
506entire matching string; if it is in the inclusive range [1..99], it is
507the string matching the the corresponding parenthesized group. If no
508such group exists, the corresponding result is
509\code{None}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000510
Guido van Rossum0b334101997-12-08 17:33:40 +0000511If the regular expression uses the \code{(?P<\var{name}>...)} syntax,
512the \var{index} arguments may also be strings identifying groups by
513their group name.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000514
515A moderately complicated example:
516\bcode\begin{verbatim}
517m = re.match(r"(?P<int>\d+)\.(\d*)", '3.14')
518\end{verbatim}\ecode
519%
520After performing this match, \code{m.group(1)} is \code{'3'}, as is \code{m.group('int')}.
521\code{m.group(2)} is \code{'14'}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000522\end{funcdesc}
523
Guido van Rossum48d04371997-12-11 20:19:08 +0000524\begin{funcdesc}{groups}{}
525Return a tuple containing all the subgroups of the match, from 1 up to
526however many groups are in the pattern. Groups that did not
527participate in the match have values of \code{None}. If the tuple
528would only be one element long, a string will be returned instead.
529\end{funcdesc}
530
Guido van Rossume4eb2231997-12-17 00:23:39 +0000531\begin{funcdesc}{start}{group}
532\end{funcdesc}
533
534\begin{funcdesc}{end}{group}
535Return the indices of the start and end of the substring
536matched by \var{group}. Return \code{None} if \var{group} exists but
537did not contribute to the match. For a match object
538\code{m}, and a group \code{g} that did contribute to the match, the
539substring matched by group \code{g} (equivalent to \code{m.group(g)}) is
540\bcode\begin{verbatim}
541 m.string[m.start(g):m.end(g)]
542\end{verbatim}\ecode
543%
544Note that
545\code{m.start(\var{group})} will equal \code{m.end(\var{group})} if
546\var{group} matched a null string. For example, after \code{m =
547re.search('b(c?)', 'cba')}, \code{m.start(0)} is 1, \code{m.end(0)} is
5482, \code{m.start(1)} and \code{m.end(1)} are both 2, and
549\code{m.start(2)} raises an \code{IndexError} exception.
550
551\end{funcdesc}
552
553\begin{funcdesc}{span}{group}
554Return the 2-tuple \code{(start(\var{group}), end(\var{group}))}.
555Note that if \var{group} did not contribute to the match, this is
556\code{(None, None)}.
557\end{funcdesc}
558
Guido van Rossum1acceb01997-08-14 23:12:18 +0000559\begin{datadesc}{pos}
Guido van Rossum0b334101997-12-08 17:33:40 +0000560The value of \var{pos} which was passed to the
561\code{search} or \code{match} function. This is the index into the
562string at which the regex engine started looking for a match.
563\end{datadesc}
564
565\begin{datadesc}{endpos}
566The value of \var{endpos} which was passed to the
567\code{search} or \code{match} function. This is the index into the
568string beyond which the regex engine will not go.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000569\end{datadesc}
570
571\begin{datadesc}{re}
Guido van Rossum48d04371997-12-11 20:19:08 +0000572The regular expression object whose \code{match()} or \code{search()} method
573produced this \code{MatchObject} instance.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000574\end{datadesc}
575
576\begin{datadesc}{string}
577The string passed to \code{match()} or \code{search()}.
578\end{datadesc}
579
Guido van Rossum1acceb01997-08-14 23:12:18 +0000580\begin{seealso}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000581\seetext Jeffrey Friedl, \emph{Mastering Regular Expressions},
582O'Reilly. The Python material in this book dates from before the re
583module, but it covers writing good regular expression patterns in
584great detail.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000585\end{seealso}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000586
587