blob: 8e273bce7f426134bb980b8ced967b0140de0979 [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 Rossum48d04371997-12-11 20:19:08 +00007{\large\bf This documentation is also 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%
121\item[\code{\e}] Either escapes special characters (permitting you to match
122characters like '*?+\&\$'), or signals a special sequence; special
123sequences are discussed below.
124
125If you're not using a raw string to
126express the pattern, remember that Python also uses the
127backslash as an escape sequence in string literals; if the escape
128sequence isn't recognized by Python's parser, the backslash and
129subsequent character are included in the resulting string. However,
130if Python would recognize the resulting sequence, the backslash should
131be repeated twice. This is complicated and hard to understand, so
Guido van Rossum48d04371997-12-11 20:19:08 +0000132it's highly recommended that you use raw strings for all but the simplest expressions.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000133%
134\item[\code{[]}] Used to indicate a set of characters. Characters can
Guido van Rossum48d04371997-12-11 20:19:08 +0000135be listed individually, or a range of characters can be indicated by
136giving two characters and separating them by a '-'. Special
137characters are not active inside sets. For example, \code{[akm\$]}
138will match any of the characters 'a', 'k', 'm', or '\$'; \code{[a-z]}
139will match any lowercase letter and \code{[a-zA-Z0-9]} matches any
140letter or digit. Character classes such as \code{\e w} or \code {\e
141S} (defined below) are also acceptable inside a range. If you want to
142include a \code{]} or a \code{-} inside a set, precede it with a
143backslash.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000144
145Characters \emph{not} within a range can be matched by including a
146\code{\^} as the first character of the set; \code{\^} elsewhere will
147simply match the '\code{\^}' character.
148%
149\item[\code{|}]\code{A|B}, where A and B can be arbitrary REs,
150creates a regular expression that will match either A or B. This can
151be used inside groups (see below) as well. To match a literal '|',
152use \code{\e|}, or enclose it inside a character class, like \code{[|]}.
153%
Guido van Rossum48d04371997-12-11 20:19:08 +0000154\item[\code{(...)}] Matches whatever regular expression is inside the
155parentheses, and indicates the start and end of a group; the contents
156of a group can be retrieved after a match has been performed, and can
157be matched later in the string with the \code{\e \var{number}} special
158sequence, described below. To match the literals '(' or ')',
Guido van Rossum1acceb01997-08-14 23:12:18 +0000159use \code{\e(} or \code{\e)}, or enclose them inside a character
160class: \code{[(] [)]}.
161%
Guido van Rossum0b334101997-12-08 17:33:40 +0000162\item[\code{(?...)}] This is an extension notation (a '?' following a
163'(' is not meaningful otherwise). The first character after the '?'
164determines what the meaning and further syntax of the construct is.
165Following are the currently supported extensions.
166%
Guido van Rossumbd49ac41997-12-10 23:05:53 +0000167\item[\code{(?iLmsx)}] (One or more letters from the set 'i', 'L', 'm', 's',
Guido van Rossum0b334101997-12-08 17:33:40 +0000168'x'.) The group matches the empty string; the letters set the
169corresponding flags (re.I, re.L, re.M, re.S, re.X) for the entire regular
Guido van Rossum48d04371997-12-11 20:19:08 +0000170expression. This is useful if you wish include the flags as part of
171the regular expression, instead of passing a \var{flag} argument to
172the \code{compile} function.
Guido van Rossum0b334101997-12-08 17:33:40 +0000173%
Guido van Rossum1acceb01997-08-14 23:12:18 +0000174\item[\code{(?:...)}] A non-grouping version of regular parentheses.
175Matches whatever's inside the parentheses, but the text matched by the
176group \emph{cannot} be retrieved after performing a match or
177referenced later in the pattern.
178%
179\item[\code{(?P<\var{name}>...)}] Similar to regular parentheses, but
180the text matched by the group is accessible via the symbolic group
181name \var{name}. Group names must be valid Python identifiers. A
182symbolic group is also a numbered group, just as if the group were not
183named. So the group named 'id' in the example above can also be
184referenced as the numbered group 1.
185
Guido van Rossum48d04371997-12-11 20:19:08 +0000186For example, if the pattern is
187\code{(?P<id>[a-zA-Z_]\e w*)}, the group can be referenced by its
Guido van Rossum1acceb01997-08-14 23:12:18 +0000188name in arguments to methods of match objects, such as \code{m.group('id')}
189or \code{m.end('id')}, and also by name in pattern text (e.g. \code{(?P=id)}) and
190replacement text (e.g. \code{\e g<id>}).
191%
Guido van Rossum48d04371997-12-11 20:19:08 +0000192\item[\code{(?P=\var{name})}] Matches whatever text was matched by the earlier group named \var{name}.
193%
Guido van Rossum1acceb01997-08-14 23:12:18 +0000194\item[\code{(?\#...)}] A comment; the contents of the parentheses are simply ignored.
195%
Guido van Rossum0b334101997-12-08 17:33:40 +0000196\item[\code{(?=...)}] Matches if \code{...} matches next, but doesn't consume any of the string. This is called a lookahead assertion. For example,
197\code{Isaac (?=Asimov)} will match 'Isaac~' only if it's followed by 'Asimov'.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000198%
Guido van Rossum0b334101997-12-08 17:33:40 +0000199\item[\code{(?!...)}] Matches if \code{...} doesn't match next. This is a negative lookahead assertion. For example,
200For example,
201\code{Isaac (?!Asimov)} will match 'Isaac~' only if it's \emph{not} followed by 'Asimov'.
202
Guido van Rossum1acceb01997-08-14 23:12:18 +0000203\end{itemize}
204
205The special sequences consist of '\code{\e}' and a character from the
206list below. If the ordinary character is not on the list, then the
207resulting RE will match the second character. For example,
Guido van Rossum48d04371997-12-11 20:19:08 +0000208\code{\e\$} matches the character '\$'.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000209
210\begin{itemize}
211
212%
213\item[\code{\e \var{number}}] Matches the contents of the group of the
Guido van Rossum0b334101997-12-08 17:33:40 +0000214same number. Groups are numbered starting from 1. For example,
215\code{(.+) \e 1} matches 'the the' or '55 55', but not 'the end' (note
216the space after the group). This special sequence can only be used to
217match one of the first 99 groups. If the first digit of \var{number}
218is 0, or \var{number} is 3 octal digits long, it will not be interpreted
219as a group match, but as the character with octal value \var{number}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000220%
221\item[\code{\e A}] Matches only at the start of the string.
222%
223\item[\code{\e b}] Matches the empty string, but only at the
224beginning or end of a word. A word is defined as a sequence of
225alphanumeric characters, so the end of a word is indicated by
Guido van Rossum48d04371997-12-11 20:19:08 +0000226whitespace or a non-alphanumeric character. Inside a character range,
227\code{\e b} represents the backspace character, for compatibility with
228Python's string literals.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000229%
Guido van Rossum0b334101997-12-08 17:33:40 +0000230\item[\code{\e B}] Matches the empty string, but only when it is
231\emph{not} at the beginning or end of a word.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000232%
233\item[\code{\e d}]Matches any decimal digit; this is
234equivalent to the set \code{[0-9]}.
235%
236\item[\code{\e D}]Matches any non-digit character; this is
Guido van Rossumd7dc2eb1997-10-22 03:03:44 +0000237equivalent to the set \code{[{\^}0-9]}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000238%
239\item[\code{\e s}]Matches any whitespace character; this is
240equivalent to the set \code{[ \e t\e n\e r\e f\e v]}.
241%
242\item[\code{\e S}]Matches any non-whitespace character; this is
Guido van Rossumd7dc2eb1997-10-22 03:03:44 +0000243equivalent to the set \code{[{\^} \e t\e n\e r\e f\e v]}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000244%
Guido van Rossum0b334101997-12-08 17:33:40 +0000245\item[\code{\e w}]When the LOCALE flag is not specified, matches any alphanumeric character; this is
246equivalent to the set \code{[a-zA-Z0-9_]}. With LOCALE, it will match
247the set \code{[0-9_]} plus whatever characters are defined as letters
248for the current locale.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000249%
Guido van Rossum0b334101997-12-08 17:33:40 +0000250\item[\code{\e W}]When the LOCALE flag is not specified, matches any
251non-alphanumeric character; this is equivalent to the set
252\code{[{\^}a-zA-Z0-9_]}. With LOCALE, it will match any character
253not in the set \code{[0-9_]}, and not defined as a letter
254for the current locale.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000255
256\item[\code{\e Z}]Matches only at the end of the string.
257%
258
259\item[\code{\e \e}] Matches a literal backslash.
260
261\end{itemize}
262
263\subsection{Module Contents}
264
265The module defines the following functions and constants, and an exception:
266
267\renewcommand{\indexsubitem}{(in module re)}
268
269\begin{funcdesc}{compile}{pattern\optional{\, flags}}
270 Compile a regular expression pattern into a regular expression
271 object, which can be used for matching using its \code{match} and
272 \code{search} methods, described below.
273
Guido van Rossum0b334101997-12-08 17:33:40 +0000274 The expression's behaviour can be modified by specifying a
275 \var{flags} value. Values can be any of the following variables,
276 combined using bitwise OR (the \code{|} operator).
277
Guido van Rossuma42c1781997-12-09 20:41:47 +0000278\begin{itemize}
Guido van Rossum0b334101997-12-08 17:33:40 +0000279
Guido van Rossum48d04371997-12-11 20:19:08 +0000280\item {I or IGNORECASE or \code{(?i)}}
Guido van Rossum0b334101997-12-08 17:33:40 +0000281
Guido van Rossum48d04371997-12-11 20:19:08 +0000282{Perform case-insensitive matching; expressions like \code{[A-Z]} will match
283lowercase letters, too. This is not affected by the current locale.
284}
285\item {L or LOCALE or \code{(?L)}}
Guido van Rossum0b334101997-12-08 17:33:40 +0000286
Guido van Rossum48d04371997-12-11 20:19:08 +0000287{Make \code{\e w}, \code{\e W}, \code{\e b},
288\code{\e B}, dependent on the current locale.
289}
Guido van Rossuma42c1781997-12-09 20:41:47 +0000290
Guido van Rossum48d04371997-12-11 20:19:08 +0000291\item {M or MULTILINE or \code{(?m)}}
292
293{When specified, the pattern character \code{\^} matches at the
294 beginning of the string and at the beginning of each line
295 (immediately following each newline); and the pattern character
296\code{\$} matches at the end of the string and at the end of each line
297(immediately preceding each newline).
Guido van Rossum0b334101997-12-08 17:33:40 +0000298By default, \code{\^} matches only at the beginning of the string, and
299\code{\$} only at the end of the string and immediately before the
300newline (if any) at the end of the string.
Guido van Rossum48d04371997-12-11 20:19:08 +0000301}
Guido van Rossum0b334101997-12-08 17:33:40 +0000302
Guido van Rossum48d04371997-12-11 20:19:08 +0000303\item {S or DOTALL or \code{(?s)}}
Guido van Rossum0b334101997-12-08 17:33:40 +0000304
Guido van Rossum48d04371997-12-11 20:19:08 +0000305{Make the \code{.} special character any character at all, including a
306newline; without this flag, \code{.} will match anything \emph{except}
307a newline.}
308
309\item {X or VERBOSE or \code{(?x)}}
310
311{Ignore whitespace within the pattern
312except when in a character class or preceded by an unescaped
313backslash, and, when a line contains a \code{\#} neither in a character
314class or preceded by an unescaped backslash, all characters from the
315leftmost such \code{\#} through the end of the line are ignored. }
Guido van Rossum0b334101997-12-08 17:33:40 +0000316
Guido van Rossuma42c1781997-12-09 20:41:47 +0000317\end{itemize}
Guido van Rossum0b334101997-12-08 17:33:40 +0000318
Guido van Rossum1acceb01997-08-14 23:12:18 +0000319 The sequence
320%
321\bcode\begin{verbatim}
322prog = re.compile(pat)
323result = prog.match(str)
324\end{verbatim}\ecode
325%
326is equivalent to
327%
328\bcode\begin{verbatim}
329result = re.match(pat, str)
330\end{verbatim}\ecode
331%
Guido van Rossum48d04371997-12-11 20:19:08 +0000332but the version using \code{compile()} is more efficient when the
333expression will be used several times in a single program.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000334%(The compiled version of the last pattern passed to \code{regex.match()} or
335%\code{regex.search()} is cached, so programs that use only a single
336%regular expression at a time needn't worry about compiling regular
337%expressions.)
338\end{funcdesc}
339
340\begin{funcdesc}{escape}{string}
Guido van Rossum48d04371997-12-11 20:19:08 +0000341 Return \var{string} with all non-alphanumerics backslashed; this is
342 useful if you want to match an arbitrary literal string that may have
343 regular expression metacharacters in it.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000344\end{funcdesc}
345
346\begin{funcdesc}{match}{pattern\, string\optional{\, flags}}
347 If zero or more characters at the beginning of \var{string} match
348 the regular expression \var{pattern}, return a corresponding
349 \code{Match} object. Return \code{None} if the string does not
350 match the pattern; note that this is different from a zero-length
351 match.
352\end{funcdesc}
353
354\begin{funcdesc}{search}{pattern\, string\optional{\, flags}}
355 Scan through \var{string} looking for a location where the regular
356 expression \var{pattern} produces a match. Return \code{None} if no
357 position in the string matches the pattern; note that this is
358 different from finding a zero-length match at some point in the string.
359\end{funcdesc}
360
361\begin{funcdesc}{split}{pattern\, string\, \optional{, maxsplit=0}}
362 Split \var{string} by the occurrences of \var{pattern}. If
363 capturing parentheses are used in pattern, then occurrences of
364 patterns or subpatterns are also returned.
365%
366\bcode\begin{verbatim}
367>>> re.split('[\W]+', 'Words, words, words.')
368['Words', 'words', 'words', '']
369>>> re.split('([\W]+)', 'Words, words, words.')
370['Words', ', ', 'words', ', ', 'words', '.', '']
371\end{verbatim}\ecode
372%
373 This function combines and extends the functionality of
Guido van Rossum0b334101997-12-08 17:33:40 +0000374 the old \code{regex.split()} and \code{regex.splitx()}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000375\end{funcdesc}
376
377\begin{funcdesc}{sub}{pattern\, repl\, string\optional{, count=0}}
378Return the string obtained by replacing the leftmost non-overlapping
379occurrences of \var{pattern} in \var{string} by the replacement
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000380\var{repl}. If the pattern isn't found, \var{string} is returned
381unchanged. \var{repl} can be a string or a function; if a function,
382it is called for every non-overlapping occurance of \var{pattern}.
Guido van Rossum0b334101997-12-08 17:33:40 +0000383The function takes a single match object argument, and returns the
384replacement string. For example:
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000385%
386\bcode\begin{verbatim}
387>>> def dashrepl(matchobj):
388... if matchobj.group(0) == '-': return ' '
389... else: return '-'
390>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
391'pro--gram files'
392\end{verbatim}\ecode
393%
Guido van Rossum0b334101997-12-08 17:33:40 +0000394The pattern may be a string or a
Guido van Rossum48d04371997-12-11 20:19:08 +0000395regex object; if you need to specify
396regular expression flags, you must use a regex object, or use
397embedded modifiers in a pattern; e.g.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000398%
399\bcode\begin{verbatim}
400sub("(?i)b+", "x", "bbbb BBBB") returns 'x x'.
401\end{verbatim}\ecode
402%
403The optional argument \var{count} is the maximum number of pattern
404occurrences to be replaced; count must be a non-negative integer, and
405the default value of 0 means to replace all occurrences.
406
407Empty matches for the pattern are replaced only when not adjacent to a
408previous match, so \code{sub('x*', '-', 'abc')} returns '-a-b-c-'.
409\end{funcdesc}
410
411\begin{funcdesc}{subn}{pattern\, repl\, string\optional{, count=0}}
412Perform the same operation as \code{sub()}, but return a tuple
413\code{(new_string, number_of_subs_made)}.
414\end{funcdesc}
415
416\begin{excdesc}{error}
417 Exception raised when a string passed to one of the functions here
418 is not a valid regular expression (e.g., unmatched parentheses) or
419 when some other error occurs during compilation or matching. (It is
420 never an error if a string contains no match for a pattern.)
421\end{excdesc}
422
423\subsection{Regular Expression Objects}
424Compiled regular expression objects support the following methods and
425attributes:
426
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000427\renewcommand{\indexsubitem}{(re method)}
Guido van Rossum0b334101997-12-08 17:33:40 +0000428\begin{funcdesc}{match}{string\optional{\, pos}\optional{\, endpos}}
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000429 If zero or more characters at the beginning of \var{string} match
430 this regular expression, return a corresponding
Guido van Rossum48d04371997-12-11 20:19:08 +0000431 \code{MatchObject} instance. Return \code{None} if the string does not
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000432 match the pattern; note that this is different from a zero-length
433 match.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000434
435 The optional second parameter \var{pos} gives an index in the string
Guido van Rossum48d04371997-12-11 20:19:08 +0000436 where the search is to start; it defaults to \code{0}. The
437 \code{'\^'} pattern character will match at the index where the
438 search is to start.
Guido van Rossum0b334101997-12-08 17:33:40 +0000439
440 The optional parameter \var{endpos} limits how far the string will
441 be searched; it will be as if the string is \var{endpos} characters
442 long, so only the characters from \var{pos} to \var{endpos} will be
443 searched for a match.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000444\end{funcdesc}
445
Guido van Rossum0b334101997-12-08 17:33:40 +0000446\begin{funcdesc}{search}{string\optional{\, pos}\optional{\, endpos}}
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000447 Scan through \var{string} looking for a location where this regular
448 expression produces a match. Return \code{None} if no
449 position in the string matches the pattern; note that this is
450 different from finding a zero-length match at some point in the string.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000451
Guido van Rossum48d04371997-12-11 20:19:08 +0000452 The optional \var{pos} and \var{endpos} parameters have the same
453 meaning as for the \code{match} method.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000454\end{funcdesc}
455
456\begin{funcdesc}{split}{string\, \optional{, maxsplit=0}}
457Identical to the \code{split} function, using the compiled pattern.
458\end{funcdesc}
459
460\begin{funcdesc}{sub}{repl\, string\optional{, count=0}}
461Identical to the \code{sub} function, using the compiled pattern.
462\end{funcdesc}
463
464\begin{funcdesc}{subn}{repl\, string\optional{, count=0}}
465Identical to the \code{subn} function, using the compiled pattern.
466\end{funcdesc}
467
468\renewcommand{\indexsubitem}{(regex attribute)}
469
470\begin{datadesc}{flags}
471The flags argument used when the regex object was compiled, or 0 if no
472flags were provided.
473\end{datadesc}
474
475\begin{datadesc}{groupindex}
476A dictionary mapping any symbolic group names (defined by
477\code{?P<\var{id}>}) to group numbers. The dictionary is empty if no
478symbolic groups were used in the pattern.
479\end{datadesc}
480
481\begin{datadesc}{pattern}
482The pattern string from which the regex object was compiled.
483\end{datadesc}
484
Guido van Rossum48d04371997-12-11 20:19:08 +0000485\subsection{MatchObjects}
486\code{Matchobject} instances support the following methods and attributes:
Guido van Rossum1acceb01997-08-14 23:12:18 +0000487
Guido van Rossum1acceb01997-08-14 23:12:18 +0000488\begin{funcdesc}{start}{group}
489\end{funcdesc}
490
491\begin{funcdesc}{end}{group}
Guido van Rossum0b334101997-12-08 17:33:40 +0000492Return the indices of the start and end of the substring
493matched by \var{group}. Return \code{None} if \var{group} exists but
494did not contribute to the match. Note that for a match object
495\code{m}, and a group \code{g} that did contribute to the match, the
496substring matched by group \code{g} is
Guido van Rossum1acceb01997-08-14 23:12:18 +0000497\bcode\begin{verbatim}
498 m.string[m.start(g):m.end(g)]
499\end{verbatim}\ecode
500%
501Note too that \code{m.start(\var{group})} will equal
502\code{m.end(\var{group})} if \var{group} matched a null string. For example,
503after \code{m = re.search('b(c?)', 'cba')}, \code{m.start(0)} is 1,
504\code{m.end(0)} is 2, \code{m.start(1)} and \code{m.end(1)} are both
5052, and \code{m.start(2)} raises an
506\code{IndexError} exception.
507\end{funcdesc}
508
Guido van Rossum0b334101997-12-08 17:33:40 +0000509\begin{funcdesc}{span}{group}
510Return the 2-tuple \code{(start(\var{group}), end(\var{group}))}.
511Note that if \var{group} did not contribute to the match, this is
512\code{(None, None)}.
513\end{funcdesc}
514
Guido van Rossum48d04371997-12-11 20:19:08 +0000515\begin{funcdesc}{group}{\optional{g1, g2, ...}}
516Returns one or more groups of the match. If there is a single
517\var{index} argument, the result is a single string; if there are
518multiple arguments, the result is a tuple with one item per argument.
519If the \var{index} is zero, the corresponding return value is the
520entire matching string; if it is in the inclusive range [1..99], it is
521the string matching the the corresponding parenthesized group. If no
522such group exists, the corresponding result is
523\code{None}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000524
Guido van Rossum0b334101997-12-08 17:33:40 +0000525If the regular expression uses the \code{(?P<\var{name}>...)} syntax,
526the \var{index} arguments may also be strings identifying groups by
527their group name.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000528\end{funcdesc}
529
Guido van Rossum48d04371997-12-11 20:19:08 +0000530\begin{funcdesc}{groups}{}
531Return a tuple containing all the subgroups of the match, from 1 up to
532however many groups are in the pattern. Groups that did not
533participate in the match have values of \code{None}. If the tuple
534would only be one element long, a string will be returned instead.
535\end{funcdesc}
536
Guido van Rossum1acceb01997-08-14 23:12:18 +0000537\begin{datadesc}{pos}
Guido van Rossum0b334101997-12-08 17:33:40 +0000538The value of \var{pos} which was passed to the
539\code{search} or \code{match} function. This is the index into the
540string at which the regex engine started looking for a match.
541\end{datadesc}
542
543\begin{datadesc}{endpos}
544The value of \var{endpos} which was passed to the
545\code{search} or \code{match} function. This is the index into the
546string beyond which the regex engine will not go.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000547\end{datadesc}
548
549\begin{datadesc}{re}
Guido van Rossum48d04371997-12-11 20:19:08 +0000550The regular expression object whose \code{match()} or \code{search()} method
551produced this \code{MatchObject} instance.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000552\end{datadesc}
553
554\begin{datadesc}{string}
555The string passed to \code{match()} or \code{search()}.
556\end{datadesc}
557
Guido van Rossum1acceb01997-08-14 23:12:18 +0000558\begin{seealso}
559\seetext Jeffrey Friedl, \emph{Mastering Regular Expressions}.
560\end{seealso}