blob: 93cd4c6961e53ad4bfb65da146bb7a09910666f6 [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
Guido van Rossum1acceb01997-08-14 23:12:18 +00006This module provides regular expression matching operations similar to
Guido van Rossum0b334101997-12-08 17:33:40 +00007those found in Perl. It's 8-bit clean: both patterns and strings may
8contain null bytes and characters whose high bit is set. It is always
9available.
Guido van Rossum1acceb01997-08-14 23:12:18 +000010
11Regular expressions use the backslash character (\code{\e}) to
12indicate special forms or to allow special characters to be used
13without invoking their special meaning. This collides with Python's
14usage of the same character for the same purpose in string literals;
15for example, to match a literal backslash, one might have to write
Guido van Rossum0b334101997-12-08 17:33:40 +000016\code{\e\e\e\e} as the pattern string, because the regular expression
17must be \code{\e\e}, and each backslash must be expressed as
18\code{\e\e} inside a regular Python string literal.
Guido van Rossum1acceb01997-08-14 23:12:18 +000019
20The solution is to use Python's raw string notation for regular
21expression patterns; backslashes are not handled in any special way in
22a string literal prefixed with 'r'. So \code{r"\e n"} is a two
23character string containing a backslash and the letter 'n', while
24\code{"\e n"} is a one-character string containing a newline. Usually
25patterns will be expressed in Python code using this raw string notation.
26
Guido van Rossum48d04371997-12-11 20:19:08 +000027\subsection{Regular Expression Syntax}
Guido van Rossum1acceb01997-08-14 23:12:18 +000028
29A regular expression (or RE) specifies a set of strings that matches
30it; the functions in this module let you check if a particular string
31matches a given regular expression (or if a given regular expression
32matches a particular string, which comes down to the same thing).
33
34Regular expressions can be concatenated to form new regular
35expressions; if \emph{A} and \emph{B} are both regular expressions,
36then \emph{AB} is also an regular expression. If a string \emph{p}
37matches A and another string \emph{q} matches B, the string \emph{pq}
38will match AB. Thus, complex expressions can easily be constructed
39from simpler primitive expressions like the ones described here. For
40details of the theory and implementation of regular expressions,
41consult the Friedl book referenced below, or almost any textbook about
42compiler construction.
43
Guido van Rossum0b334101997-12-08 17:33:40 +000044A brief explanation of the format of regular expressions follows.
45%For further information and a gentler presentation, consult XXX somewhere.
Guido van Rossum1acceb01997-08-14 23:12:18 +000046
47Regular expressions can contain both special and ordinary characters.
48Most ordinary characters, like '\code{A}', '\code{a}', or '\code{0}',
49are the simplest regular expressions; they simply match themselves.
50You can concatenate ordinary characters, so '\code{last}' matches the
51characters 'last'. (In the rest of this section, we'll write RE's in
52\code{this special font}, usually without quotes, and strings to be
53matched 'in single quotes'.)
54
55Some characters, like \code{|} or \code{(}, are special. Special
56characters either stand for classes of ordinary characters, or affect
57how the regular expressions around them are interpreted.
58
59The special characters are:
60\begin{itemize}
61\item[\code{.}] (Dot.) In the default mode, this matches any
62character except a newline. If the \code{DOTALL} flag has been
63specified, this matches any character including a newline.
64\item[\code{\^}] (Caret.) Matches the start of the string, and in
65\code{MULTILINE} mode also immediately after each newline.
Guido van Rossum48d04371997-12-11 20:19:08 +000066\item[\code{\$}] Matches the end of the string, and in
67\code{MULTILINE} mode also matches before a newline.
Guido van Rossum1acceb01997-08-14 23:12:18 +000068\code{foo} matches both 'foo' and 'foobar', while the regular
Guido van Rossum48d04371997-12-11 20:19:08 +000069expression \code{foo\$} matches only 'foo'.
Guido van Rossum1acceb01997-08-14 23:12:18 +000070%
71\item[\code{*}] Causes the resulting RE to
72match 0 or more repetitions of the preceding RE, as many repetitions
73as are possible. \code{ab*} will
74match 'a', 'ab', or 'a' followed by any number of 'b's.
75%
76\item[\code{+}] Causes the
77resulting RE to match 1 or more repetitions of the preceding RE.
78\code{ab+} will match 'a' followed by any non-zero number of 'b's; it
79will not match just 'a'.
80%
81\item[\code{?}] Causes the resulting RE to
82match 0 or 1 repetitions of the preceding RE. \code{ab?} will
83match either 'a' or 'ab'.
84\item[\code{*?}, \code{+?}, \code{??}] The \code{*}, \code{+}, and
85\code{?} qualifiers are all \dfn{greedy}; they match as much text as
86possible. Sometimes this behaviour isn't desired; if the RE
87\code{<.*>} is matched against \code{<H1>title</H1>}, it will match the
88entire string, and not just \code{<H1>}.
89Adding \code{?} after the qualifier makes it perform the match in
90\dfn{non-greedy} or \dfn{minimal} fashion; as few characters as
91possible will be matched. Using \code{.*?} in the previous
Guido van Rossum0b334101997-12-08 17:33:40 +000092expression will match only \code{<H1>}.
Guido van Rossum1acceb01997-08-14 23:12:18 +000093%
Guido van Rossum0148bbf1997-12-22 22:41:40 +000094\item[\code{\{\var{m},\var{n}\}}] Causes the resulting RE to match from
95\var{m} to \var{n} repetitions of the preceding RE, attempting to
96match as many repetitions as possible. For example, \code{a\{3,5\}}
97will match from 3 to 5 'a' characters.
98%
99\item[\code{\{\var{m},\var{n}\}?}] Causes the resulting RE to
100match from \var{m} to \var{n} repetitions of the preceding RE,
101attempting to match as \emph{few} repetitions as possible. This is
102the non-greedy version of the previous qualifier. For example, on the
1036-character string 'aaaaaa', \code{a\{3,5\}} will match 5 'a'
104characters, while \code{a\{3,5\}?} will only match 3 characters.
105%
Guido van Rossum1acceb01997-08-14 23:12:18 +0000106\item[\code{\e}] Either escapes special characters (permitting you to match
107characters like '*?+\&\$'), or signals a special sequence; special
108sequences are discussed below.
109
110If you're not using a raw string to
111express the pattern, remember that Python also uses the
112backslash as an escape sequence in string literals; if the escape
113sequence isn't recognized by Python's parser, the backslash and
114subsequent character are included in the resulting string. However,
115if Python would recognize the resulting sequence, the backslash should
Fred Drake023f87f1998-01-12 19:16:24 +0000116be repeated twice. This is complicated and hard to understand, so
117it's highly recommended that you use raw strings for all but the
118simplest expressions.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000119%
120\item[\code{[]}] Used to indicate a set of characters. Characters can
Guido van Rossum48d04371997-12-11 20:19:08 +0000121be listed individually, or a range of characters can be indicated by
122giving two characters and separating them by a '-'. Special
123characters are not active inside sets. For example, \code{[akm\$]}
124will match any of the characters 'a', 'k', 'm', or '\$'; \code{[a-z]}
125will match any lowercase letter and \code{[a-zA-Z0-9]} matches any
126letter or digit. Character classes such as \code{\e w} or \code {\e
127S} (defined below) are also acceptable inside a range. If you want to
128include a \code{]} or a \code{-} inside a set, precede it with a
129backslash.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000130
131Characters \emph{not} within a range can be matched by including a
132\code{\^} as the first character of the set; \code{\^} elsewhere will
133simply match the '\code{\^}' character.
134%
135\item[\code{|}]\code{A|B}, where A and B can be arbitrary REs,
136creates a regular expression that will match either A or B. This can
Guido van Rossumeb0f0661997-12-30 20:38:16 +0000137be used inside groups (see below) as well. To match a literal '\code{|}',
Guido van Rossum1acceb01997-08-14 23:12:18 +0000138use \code{\e|}, or enclose it inside a character class, like \code{[|]}.
139%
Guido van Rossum48d04371997-12-11 20:19:08 +0000140\item[\code{(...)}] Matches whatever regular expression is inside the
141parentheses, and indicates the start and end of a group; the contents
142of a group can be retrieved after a match has been performed, and can
143be matched later in the string with the \code{\e \var{number}} special
144sequence, described below. To match the literals '(' or ')',
Guido van Rossum1acceb01997-08-14 23:12:18 +0000145use \code{\e(} or \code{\e)}, or enclose them inside a character
146class: \code{[(] [)]}.
147%
Guido van Rossum0b334101997-12-08 17:33:40 +0000148\item[\code{(?...)}] This is an extension notation (a '?' following a
149'(' is not meaningful otherwise). The first character after the '?'
150determines what the meaning and further syntax of the construct is.
151Following are the currently supported extensions.
152%
Fred Drake023f87f1998-01-12 19:16:24 +0000153\item[\code{(?iLmsx)}] (One or more letters from the set '\code{i}',
154'\code{L}', '\code{m}', '\code{s}', '\code{x}'.) The group matches
155the empty string; the letters set the corresponding flags
156(\code{re.I}, \code{re.L}, \code{re.M}, \code{re.S}, \code{re.X}) for
157the entire regular expression. This is useful if you wish include the
158flags as part of the regular expression, instead of passing a
159\var{flag} argument to the \code{compile()} function.
Guido van Rossum0b334101997-12-08 17:33:40 +0000160%
Guido van Rossum1acceb01997-08-14 23:12:18 +0000161\item[\code{(?:...)}] A non-grouping version of regular parentheses.
162Matches whatever's inside the parentheses, but the text matched by the
163group \emph{cannot} be retrieved after performing a match or
164referenced later in the pattern.
165%
166\item[\code{(?P<\var{name}>...)}] Similar to regular parentheses, but
167the text matched by the group is accessible via the symbolic group
168name \var{name}. Group names must be valid Python identifiers. A
169symbolic group is also a numbered group, just as if the group were not
170named. So the group named 'id' in the example above can also be
171referenced as the numbered group 1.
172
Guido van Rossum48d04371997-12-11 20:19:08 +0000173For example, if the pattern is
174\code{(?P<id>[a-zA-Z_]\e w*)}, the group can be referenced by its
Guido van Rossum1acceb01997-08-14 23:12:18 +0000175name in arguments to methods of match objects, such as \code{m.group('id')}
Fred Drake023f87f1998-01-12 19:16:24 +0000176or \code{m.end('id')}, and also by name in pattern text
177(e.g. \code{(?P=id)}) and replacement text (e.g. \code{\e g<id>}).
Guido van Rossum1acceb01997-08-14 23:12:18 +0000178%
Fred Drake023f87f1998-01-12 19:16:24 +0000179\item[\code{(?P=\var{name})}] Matches whatever text was matched by the
180earlier group named \var{name}.
Guido van Rossum48d04371997-12-11 20:19:08 +0000181%
Fred Drake023f87f1998-01-12 19:16:24 +0000182\item[\code{(?\#...)}] A comment; the contents of the parentheses are
183simply ignored.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000184%
Fred Drake023f87f1998-01-12 19:16:24 +0000185\item[\code{(?=...)}] Matches if \code{...} matches next, but doesn't
186consume any of the string. This is called a lookahead assertion. For
187example, \code{Isaac (?=Asimov)} will match 'Isaac~' only if it's
188followed by 'Asimov'.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000189%
Fred Drake023f87f1998-01-12 19:16:24 +0000190\item[\code{(?!...)}] Matches if \code{...} doesn't match next. This
191is a negative lookahead assertion. For example,
192\code{Isaac (?!Asimov)} will match 'Isaac~' only if it's \emph{not}
193followed by 'Asimov'.
Guido van Rossum0b334101997-12-08 17:33:40 +0000194
Guido van Rossum1acceb01997-08-14 23:12:18 +0000195\end{itemize}
196
197The special sequences consist of '\code{\e}' and a character from the
198list below. If the ordinary character is not on the list, then the
199resulting RE will match the second character. For example,
Guido van Rossum48d04371997-12-11 20:19:08 +0000200\code{\e\$} matches the character '\$'.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000201
202\begin{itemize}
203
204%
205\item[\code{\e \var{number}}] Matches the contents of the group of the
Guido van Rossum0b334101997-12-08 17:33:40 +0000206same number. Groups are numbered starting from 1. For example,
207\code{(.+) \e 1} matches 'the the' or '55 55', but not 'the end' (note
208the space after the group). This special sequence can only be used to
209match one of the first 99 groups. If the first digit of \var{number}
210is 0, or \var{number} is 3 octal digits long, it will not be interpreted
211as a group match, but as the character with octal value \var{number}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000212%
213\item[\code{\e A}] Matches only at the start of the string.
214%
215\item[\code{\e b}] Matches the empty string, but only at the
216beginning or end of a word. A word is defined as a sequence of
217alphanumeric characters, so the end of a word is indicated by
Guido van Rossum48d04371997-12-11 20:19:08 +0000218whitespace or a non-alphanumeric character. Inside a character range,
219\code{\e b} represents the backspace character, for compatibility with
220Python's string literals.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000221%
Guido van Rossum0b334101997-12-08 17:33:40 +0000222\item[\code{\e B}] Matches the empty string, but only when it is
223\emph{not} at the beginning or end of a word.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000224%
225\item[\code{\e d}]Matches any decimal digit; this is
226equivalent to the set \code{[0-9]}.
227%
228\item[\code{\e D}]Matches any non-digit character; this is
Fred Drakec4586381998-01-06 15:46:21 +0000229equivalent to the set \code{[{\^}0-9]}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000230%
231\item[\code{\e s}]Matches any whitespace character; this is
232equivalent to the set \code{[ \e t\e n\e r\e f\e v]}.
233%
234\item[\code{\e S}]Matches any non-whitespace character; this is
Fred Drake78f8e981997-12-29 21:39:39 +0000235equivalent to the set \code{[\^ \e t\e n\e r\e f\e v]}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000236%
Fred Drake023f87f1998-01-12 19:16:24 +0000237\item[\code{\e w}]When the \code{LOCALE} flag is not specified,
238matches any alphanumeric character; this is equivalent to the set
239\code{[a-zA-Z0-9_]}. With \code{LOCALE}, it will match the set
240\code{[0-9_]} plus whatever characters are defined as letters for the
241current locale.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000242%
Fred Drake023f87f1998-01-12 19:16:24 +0000243\item[\code{\e W}]When the \code{LOCALE} flag is not specified,
244matches any non-alphanumeric character; this is equivalent to the set
245\code{[{\^}a-zA-Z0-9_]}. With \code{LOCALE}, it will match any
246character not in the set \code{[0-9_]}, and not defined as a letter
Guido van Rossum0b334101997-12-08 17:33:40 +0000247for the current locale.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000248
249\item[\code{\e Z}]Matches only at the end of the string.
250%
251
252\item[\code{\e \e}] Matches a literal backslash.
253
254\end{itemize}
255
256\subsection{Module Contents}
Fred Drake78f8e981997-12-29 21:39:39 +0000257\nodename{Contents of Module re}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000258
259The module defines the following functions and constants, and an exception:
260
261\renewcommand{\indexsubitem}{(in module re)}
262
263\begin{funcdesc}{compile}{pattern\optional{\, flags}}
264 Compile a regular expression pattern into a regular expression
Fred Drake023f87f1998-01-12 19:16:24 +0000265 object, which can be used for matching using its \code{match()} and
266 \code{search()} methods, described below.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000267
Guido van Rossum0b334101997-12-08 17:33:40 +0000268 The expression's behaviour can be modified by specifying a
269 \var{flags} value. Values can be any of the following variables,
270 combined using bitwise OR (the \code{|} operator).
271
Fred Drake78f8e981997-12-29 21:39:39 +0000272\begin{description}
Guido van Rossum0b334101997-12-08 17:33:40 +0000273
Fred Drake78f8e981997-12-29 21:39:39 +0000274% The use of \quad in the item labels is ugly but adds enough space
275% to the label that it doesn't get visually run-in with the text.
Guido van Rossum0b334101997-12-08 17:33:40 +0000276
Fred Drake023f87f1998-01-12 19:16:24 +0000277\item[\code{I} or \code{IGNORECASE} or \code{(?i)}\quad]
Fred Drake78f8e981997-12-29 21:39:39 +0000278
279Perform case-insensitive matching; expressions like \code{[A-Z]} will match
Guido van Rossum48d04371997-12-11 20:19:08 +0000280lowercase letters, too. This is not affected by the current locale.
Guido van Rossum0b334101997-12-08 17:33:40 +0000281
Fred Drake023f87f1998-01-12 19:16:24 +0000282\item[\code{L} or \code{LOCALE} or \code{(?L)}\quad]
Fred Drake78f8e981997-12-29 21:39:39 +0000283
284Make \code{\e w}, \code{\e W}, \code{\e b},
Guido van Rossum48d04371997-12-11 20:19:08 +0000285\code{\e B}, dependent on the current locale.
Guido van Rossuma42c1781997-12-09 20:41:47 +0000286
Fred Drake023f87f1998-01-12 19:16:24 +0000287\item[\code{M} or \code{MULTILINE} or \code{(?m)}\quad]
Guido van Rossum48d04371997-12-11 20:19:08 +0000288
Fred Drake78f8e981997-12-29 21:39:39 +0000289When specified, the pattern character \code{\^} matches at the
Fred Drake023f87f1998-01-12 19:16:24 +0000290beginning of the string and at the beginning of each line
291(immediately following each newline); and the pattern character
Guido van Rossum48d04371997-12-11 20:19:08 +0000292\code{\$} matches at the end of the string and at the end of each line
293(immediately preceding each newline).
Guido van Rossum0b334101997-12-08 17:33:40 +0000294By default, \code{\^} matches only at the beginning of the string, and
295\code{\$} only at the end of the string and immediately before the
296newline (if any) at the end of the string.
Guido van Rossum0b334101997-12-08 17:33:40 +0000297
Fred Drake023f87f1998-01-12 19:16:24 +0000298\item[\code{S} or \code{DOTALL} or \code{(?s)}\quad]
Guido van Rossum0b334101997-12-08 17:33:40 +0000299
Fred Drake78f8e981997-12-29 21:39:39 +0000300Make the \code{.} special character any character at all, including a
Guido van Rossum48d04371997-12-11 20:19:08 +0000301newline; without this flag, \code{.} will match anything \emph{except}
Fred Drake78f8e981997-12-29 21:39:39 +0000302a newline.
Guido van Rossum48d04371997-12-11 20:19:08 +0000303
Fred Drake023f87f1998-01-12 19:16:24 +0000304\item[\code{X} or \code{VERBOSE} or \code{(?x)}\quad]
Guido van Rossum48d04371997-12-11 20:19:08 +0000305
Fred Drake78f8e981997-12-29 21:39:39 +0000306Ignore whitespace within the pattern
Guido van Rossum48d04371997-12-11 20:19:08 +0000307except when in a character class or preceded by an unescaped
308backslash, and, when a line contains a \code{\#} neither in a character
309class or preceded by an unescaped backslash, all characters from the
Fred Drake78f8e981997-12-29 21:39:39 +0000310leftmost such \code{\#} through the end of the line are ignored.
Guido van Rossum0b334101997-12-08 17:33:40 +0000311
Fred Drake78f8e981997-12-29 21:39:39 +0000312\end{description}
Guido van Rossum0b334101997-12-08 17:33:40 +0000313
Fred Drake78f8e981997-12-29 21:39:39 +0000314The sequence
Guido van Rossum1acceb01997-08-14 23:12:18 +0000315%
316\bcode\begin{verbatim}
317prog = re.compile(pat)
318result = prog.match(str)
319\end{verbatim}\ecode
320%
321is equivalent to
Fred Drake023f87f1998-01-12 19:16:24 +0000322
323\begin{verbatim}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000324result = re.match(pat, str)
Fred Drake023f87f1998-01-12 19:16:24 +0000325\end{verbatim}
326
Guido van Rossum48d04371997-12-11 20:19:08 +0000327but the version using \code{compile()} is more efficient when the
328expression will be used several times in a single program.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000329%(The compiled version of the last pattern passed to \code{regex.match()} or
330%\code{regex.search()} is cached, so programs that use only a single
331%regular expression at a time needn't worry about compiling regular
332%expressions.)
333\end{funcdesc}
334
335\begin{funcdesc}{escape}{string}
Guido van Rossum48d04371997-12-11 20:19:08 +0000336 Return \var{string} with all non-alphanumerics backslashed; this is
337 useful if you want to match an arbitrary literal string that may have
338 regular expression metacharacters in it.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000339\end{funcdesc}
340
341\begin{funcdesc}{match}{pattern\, string\optional{\, flags}}
342 If zero or more characters at the beginning of \var{string} match
343 the regular expression \var{pattern}, return a corresponding
Guido van Rossum0148bbf1997-12-22 22:41:40 +0000344 \code{MatchObject} instance. Return \code{None} if the string does not
Guido van Rossum1acceb01997-08-14 23:12:18 +0000345 match the pattern; note that this is different from a zero-length
346 match.
347\end{funcdesc}
348
349\begin{funcdesc}{search}{pattern\, string\optional{\, flags}}
350 Scan through \var{string} looking for a location where the regular
Fred Drake023f87f1998-01-12 19:16:24 +0000351 expression \var{pattern} produces a match, and return a
352 corresponding \code{MatchObject} instance.
Guido van Rossum0148bbf1997-12-22 22:41:40 +0000353 Return \code{None} if no
Guido van Rossum1acceb01997-08-14 23:12:18 +0000354 position in the string matches the pattern; note that this is
355 different from finding a zero-length match at some point in the string.
356\end{funcdesc}
357
358\begin{funcdesc}{split}{pattern\, string\, \optional{, maxsplit=0}}
359 Split \var{string} by the occurrences of \var{pattern}. If
360 capturing parentheses are used in pattern, then occurrences of
361 patterns or subpatterns are also returned.
Guido van Rossum97546391998-01-12 18:58:53 +0000362 If \var{maxsplit} is nonzero, at most \var{maxsplit} splits
363 occur, and the remainder of the string is returned as the final
364 element of the list. (Incompatibility note: in the original Python
365 1.5 release, \var{maxsplit} was ignored. This has been fixed in
366 later releases.)
Guido van Rossum1acceb01997-08-14 23:12:18 +0000367%
368\bcode\begin{verbatim}
369>>> re.split('[\W]+', 'Words, words, words.')
370['Words', 'words', 'words', '']
371>>> re.split('([\W]+)', 'Words, words, words.')
372['Words', ', ', 'words', ', ', 'words', '.', '']
Guido van Rossum97546391998-01-12 18:58:53 +0000373>>> re.split('[\W]+', 'Words, words, words.', 1)
374['Words', 'words, words.']
Guido van Rossum1acceb01997-08-14 23:12:18 +0000375\end{verbatim}\ecode
376%
377 This function combines and extends the functionality of
Guido van Rossum97546391998-01-12 18:58:53 +0000378 the old \code{regsub.split()} and \code{regsub.splitx()}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000379\end{funcdesc}
380
381\begin{funcdesc}{sub}{pattern\, repl\, string\optional{, count=0}}
382Return the string obtained by replacing the leftmost non-overlapping
383occurrences of \var{pattern} in \var{string} by the replacement
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000384\var{repl}. If the pattern isn't found, \var{string} is returned
385unchanged. \var{repl} can be a string or a function; if a function,
386it is called for every non-overlapping occurance of \var{pattern}.
Guido van Rossum0b334101997-12-08 17:33:40 +0000387The function takes a single match object argument, and returns the
388replacement string. For example:
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000389%
390\bcode\begin{verbatim}
391>>> def dashrepl(matchobj):
392... if matchobj.group(0) == '-': return ' '
393... else: return '-'
394>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
395'pro--gram files'
396\end{verbatim}\ecode
397%
Guido van Rossum0b334101997-12-08 17:33:40 +0000398The pattern may be a string or a
Guido van Rossum48d04371997-12-11 20:19:08 +0000399regex object; if you need to specify
400regular expression flags, you must use a regex object, or use
401embedded modifiers in a pattern; e.g.
Fred Drake023f87f1998-01-12 19:16:24 +0000402
403\begin{verbatim}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000404sub("(?i)b+", "x", "bbbb BBBB") returns 'x x'.
Fred Drake023f87f1998-01-12 19:16:24 +0000405\end{verbatim}
406
Guido van Rossum1acceb01997-08-14 23:12:18 +0000407The optional argument \var{count} is the maximum number of pattern
408occurrences to be replaced; count must be a non-negative integer, and
409the default value of 0 means to replace all occurrences.
410
411Empty matches for the pattern are replaced only when not adjacent to a
412previous match, so \code{sub('x*', '-', 'abc')} returns '-a-b-c-'.
413\end{funcdesc}
414
415\begin{funcdesc}{subn}{pattern\, repl\, string\optional{, count=0}}
416Perform the same operation as \code{sub()}, but return a tuple
Fred Drake023f87f1998-01-12 19:16:24 +0000417\code{(\var{new_string}, \var{number_of_subs_made})}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000418\end{funcdesc}
419
420\begin{excdesc}{error}
421 Exception raised when a string passed to one of the functions here
422 is not a valid regular expression (e.g., unmatched parentheses) or
423 when some other error occurs during compilation or matching. (It is
424 never an error if a string contains no match for a pattern.)
425\end{excdesc}
426
427\subsection{Regular Expression Objects}
428Compiled regular expression objects support the following methods and
429attributes:
430
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000431\renewcommand{\indexsubitem}{(re method)}
Guido van Rossum0b334101997-12-08 17:33:40 +0000432\begin{funcdesc}{match}{string\optional{\, pos}\optional{\, endpos}}
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000433 If zero or more characters at the beginning of \var{string} match
434 this regular expression, return a corresponding
Guido van Rossum48d04371997-12-11 20:19:08 +0000435 \code{MatchObject} instance. Return \code{None} if the string does not
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000436 match the pattern; note that this is different from a zero-length
437 match.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000438
439 The optional second parameter \var{pos} gives an index in the string
Guido van Rossum48d04371997-12-11 20:19:08 +0000440 where the search is to start; it defaults to \code{0}. The
441 \code{'\^'} pattern character will match at the index where the
442 search is to start.
Guido van Rossum0b334101997-12-08 17:33:40 +0000443
444 The optional parameter \var{endpos} limits how far the string will
445 be searched; it will be as if the string is \var{endpos} characters
446 long, so only the characters from \var{pos} to \var{endpos} will be
447 searched for a match.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000448\end{funcdesc}
449
Guido van Rossum0b334101997-12-08 17:33:40 +0000450\begin{funcdesc}{search}{string\optional{\, pos}\optional{\, endpos}}
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000451 Scan through \var{string} looking for a location where this regular
452 expression produces a match. Return \code{None} if no
453 position in the string matches the pattern; note that this is
454 different from finding a zero-length match at some point in the string.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000455
Guido van Rossum48d04371997-12-11 20:19:08 +0000456 The optional \var{pos} and \var{endpos} parameters have the same
Fred Drake023f87f1998-01-12 19:16:24 +0000457 meaning as for the \code{match()} method.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000458\end{funcdesc}
459
460\begin{funcdesc}{split}{string\, \optional{, maxsplit=0}}
Fred Drake023f87f1998-01-12 19:16:24 +0000461Identical to the \code{split()} function, using the compiled pattern.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000462\end{funcdesc}
463
464\begin{funcdesc}{sub}{repl\, string\optional{, count=0}}
Fred Drake023f87f1998-01-12 19:16:24 +0000465Identical to the \code{sub()} function, using the compiled pattern.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000466\end{funcdesc}
467
468\begin{funcdesc}{subn}{repl\, string\optional{, count=0}}
Fred Drake023f87f1998-01-12 19:16:24 +0000469Identical to the \code{subn()} function, using the compiled pattern.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000470\end{funcdesc}
471
472\renewcommand{\indexsubitem}{(regex attribute)}
473
474\begin{datadesc}{flags}
475The flags argument used when the regex object was compiled, or 0 if no
476flags were provided.
477\end{datadesc}
478
479\begin{datadesc}{groupindex}
480A dictionary mapping any symbolic group names (defined by
481\code{?P<\var{id}>}) to group numbers. The dictionary is empty if no
482symbolic groups were used in the pattern.
483\end{datadesc}
484
485\begin{datadesc}{pattern}
486The pattern string from which the regex object was compiled.
487\end{datadesc}
488
Fred Drake023f87f1998-01-12 19:16:24 +0000489\subsection{Match Objects}
490
491\code{MatchObject} instances support the following methods and attributes:
Guido van Rossum1acceb01997-08-14 23:12:18 +0000492
Guido van Rossum46503921998-01-19 23:14:17 +0000493\begin{funcdesc}{group}{\optional{group1, group2, ...}}
494Returns one or more subgroups of the match. If there is a single
495argument, the result is a single string; if there are
Guido van Rossum48d04371997-12-11 20:19:08 +0000496multiple arguments, the result is a tuple with one item per argument.
Guido van Rossum46503921998-01-19 23:14:17 +0000497Without arguments, \var{group1} defaults to zero (i.e. the whole match
498is returned).
499If a \var{groupN} argument is zero, the corresponding return value is the
Guido van Rossum48d04371997-12-11 20:19:08 +0000500entire matching string; if it is in the inclusive range [1..99], it is
501the string matching the the corresponding parenthesized group. If no
502such group exists, the corresponding result is
503\code{None}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000504
Guido van Rossum0b334101997-12-08 17:33:40 +0000505If the regular expression uses the \code{(?P<\var{name}>...)} syntax,
Guido van Rossum46503921998-01-19 23:14:17 +0000506the \var{groupN} arguments may also be strings identifying groups by
Guido van Rossum0b334101997-12-08 17:33:40 +0000507their group name.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000508
509A moderately complicated example:
Fred Drake023f87f1998-01-12 19:16:24 +0000510
511\begin{verbatim}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000512m = re.match(r"(?P<int>\d+)\.(\d*)", '3.14')
Fred Drake023f87f1998-01-12 19:16:24 +0000513\end{verbatim}
514
515After performing this match, \code{m.group(1)} is \code{'3'}, as is
Guido van Rossum46503921998-01-19 23:14:17 +0000516\code{m.group('int')}, and \code{m.group(2)} is \code{'14'}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000517\end{funcdesc}
518
Guido van Rossum48d04371997-12-11 20:19:08 +0000519\begin{funcdesc}{groups}{}
520Return a tuple containing all the subgroups of the match, from 1 up to
521however many groups are in the pattern. Groups that did not
Guido van Rossum97546391998-01-12 18:58:53 +0000522participate in the match have values of \code{None}. (Incompatibility
523note: in the original Python 1.5 release, if the tuple was one element
524long, a string would be returned instead. In later versions, a
525singleton tuple is returned in such cases.)
Guido van Rossum48d04371997-12-11 20:19:08 +0000526\end{funcdesc}
527
Guido van Rossum46503921998-01-19 23:14:17 +0000528\begin{funcdesc}{start}{\optional{group}}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000529\end{funcdesc}
530
Guido van Rossum46503921998-01-19 23:14:17 +0000531\begin{funcdesc}{end}{\optional{group}}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000532Return the indices of the start and end of the substring
Guido van Rossum46503921998-01-19 23:14:17 +0000533matched by \var{group}; \var{group} defaults to zero (meaning the whole
534matched substring).
535Return \code{None} if \var{group} exists but
Guido van Rossume4eb2231997-12-17 00:23:39 +0000536did not contribute to the match. For a match object
Fred Drake023f87f1998-01-12 19:16:24 +0000537\var{m}, and a group \var{g} that did contribute to the match, the
538substring matched by group \var{g} (equivalent to
539\code{\var{m}.group(\var{g})}) is
540
541\begin{verbatim}
542m.string[m.start(g):m.end(g)]
543\end{verbatim}
544
Guido van Rossume4eb2231997-12-17 00:23:39 +0000545Note that
546\code{m.start(\var{group})} will equal \code{m.end(\var{group})} if
Fred Drake023f87f1998-01-12 19:16:24 +0000547\var{group} matched a null string. For example, after \code{\var{m} =
548re.search('b(c?)', 'cba')}, \code{\var{m}.start(0)} is 1,
549\code{\var{m}.end(0)} is 2, \code{\var{m}.start(1)} and
550\code{\var{m}.end(1)} are both 2, and \code{\var{m}.start(2)} raises
551an \code{IndexError} exception.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000552
553\end{funcdesc}
554
Guido van Rossum46503921998-01-19 23:14:17 +0000555\begin{funcdesc}{span}{\optional{group}}
Fred Drake023f87f1998-01-12 19:16:24 +0000556For \code{MatchObject} \var{m}, return the 2-tuple
557\code{(\var{m}.start(\var{group}), \var{m}.end(\var{group}))}.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000558Note that if \var{group} did not contribute to the match, this is
Guido van Rossum46503921998-01-19 23:14:17 +0000559\code{(None, None)}. Again, \var{group} defaults to zero.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000560\end{funcdesc}
561
Guido van Rossum1acceb01997-08-14 23:12:18 +0000562\begin{datadesc}{pos}
Guido van Rossum0b334101997-12-08 17:33:40 +0000563The value of \var{pos} which was passed to the
Fred Drake023f87f1998-01-12 19:16:24 +0000564\code{search()} or \code{match()} function. This is the index into
565the string at which the regex engine started looking for a match.
Guido van Rossum0b334101997-12-08 17:33:40 +0000566\end{datadesc}
567
568\begin{datadesc}{endpos}
569The value of \var{endpos} which was passed to the
Fred Drake023f87f1998-01-12 19:16:24 +0000570\code{search()} or \code{match()} function. This is the index into
571the string beyond which the regex engine will not go.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000572\end{datadesc}
573
574\begin{datadesc}{re}
Guido van Rossum48d04371997-12-11 20:19:08 +0000575The regular expression object whose \code{match()} or \code{search()} method
576produced this \code{MatchObject} instance.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000577\end{datadesc}
578
579\begin{datadesc}{string}
580The string passed to \code{match()} or \code{search()}.
581\end{datadesc}
582
Guido van Rossum1acceb01997-08-14 23:12:18 +0000583\begin{seealso}
Fred Drakef9951811997-12-29 16:37:04 +0000584\seetext{Jeffrey Friedl, \emph{Mastering Regular Expressions},
Fred Drake023f87f1998-01-12 19:16:24 +0000585O'Reilly. The Python material in this book dates from before the
586\code{re} module, but it covers writing good regular expression
587patterns in great detail.}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000588\end{seealso}