blob: f04f4dccc46385445e2a6c80964ba646a074734a [file] [log] [blame]
Fred Drake3a0351c1998-04-04 07:23:21 +00001\section{Built-in Module \module{re}}
Guido van Rossum1acceb01997-08-14 23:12:18 +00002\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
Fred Drake20e01961998-02-19 15:09:35 +000011Regular expressions use the backslash character (\samp{\e}) to
Guido van Rossum1acceb01997-08-14 23:12:18 +000012indicate 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
Fred Drake20e01961998-02-19 15:09:35 +000016\samp{\e\e\e\e} as the pattern string, because the regular expression
17must be \samp{\e\e}, and each backslash must be expressed as
18\samp{\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.
Fred Drake20e01961998-02-19 15:09:35 +000048Most ordinary characters, like \samp{A}, \samp{a}, or \samp{0},
Guido van Rossum1acceb01997-08-14 23:12:18 +000049are the simplest regular expressions; they simply match themselves.
Fred Drake20e01961998-02-19 15:09:35 +000050You can concatenate ordinary characters, so \samp{last} matches the
Guido van Rossum1acceb01997-08-14 23:12:18 +000051characters '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
Fred Drake20e01961998-02-19 15:09:35 +000055Some characters, like \samp{|} or \samp{(}, are special. Special
Guido van Rossum1acceb01997-08-14 23:12:18 +000056characters either stand for classes of ordinary characters, or affect
57how the regular expressions around them are interpreted.
58
59The special characters are:
Fred Drake2705e801998-02-16 21:21:13 +000060% define these since they're used twice:
61\newcommand{\MyLeftMargin}{0.7in}
62\newcommand{\MyLabelWidth}{0.65in}
63\begin{list}{}{\leftmargin \MyLeftMargin \labelwidth \MyLabelWidth}
Guido van Rossum1acceb01997-08-14 23:12:18 +000064\item[\code{.}] (Dot.) In the default mode, this matches any
Fred Drake20e01961998-02-19 15:09:35 +000065character except a newline. If the \constant{DOTALL} flag has been
Guido van Rossum1acceb01997-08-14 23:12:18 +000066specified, this matches any character including a newline.
Fred Drake20e01961998-02-19 15:09:35 +000067%
Guido van Rossum1acceb01997-08-14 23:12:18 +000068\item[\code{\^}] (Caret.) Matches the start of the string, and in
Fred Drake20e01961998-02-19 15:09:35 +000069\constant{MULTILINE} mode also immediately after each newline.
70%
Guido van Rossum48d04371997-12-11 20:19:08 +000071\item[\code{\$}] Matches the end of the string, and in
Fred Drake20e01961998-02-19 15:09:35 +000072\constant{MULTILINE} mode also matches before a newline.
Guido van Rossum1acceb01997-08-14 23:12:18 +000073\code{foo} matches both 'foo' and 'foobar', while the regular
Guido van Rossum48d04371997-12-11 20:19:08 +000074expression \code{foo\$} matches only 'foo'.
Guido van Rossum1acceb01997-08-14 23:12:18 +000075%
76\item[\code{*}] Causes the resulting RE to
77match 0 or more repetitions of the preceding RE, as many repetitions
78as are possible. \code{ab*} will
79match 'a', 'ab', or 'a' followed by any number of 'b's.
80%
81\item[\code{+}] Causes the
82resulting RE to match 1 or more repetitions of the preceding RE.
83\code{ab+} will match 'a' followed by any non-zero number of 'b's; it
84will not match just 'a'.
85%
86\item[\code{?}] Causes the resulting RE to
87match 0 or 1 repetitions of the preceding RE. \code{ab?} will
88match either 'a' or 'ab'.
89\item[\code{*?}, \code{+?}, \code{??}] The \code{*}, \code{+}, and
90\code{?} qualifiers are all \dfn{greedy}; they match as much text as
91possible. Sometimes this behaviour isn't desired; if the RE
92\code{<.*>} is matched against \code{<H1>title</H1>}, it will match the
93entire string, and not just \code{<H1>}.
94Adding \code{?} after the qualifier makes it perform the match in
95\dfn{non-greedy} or \dfn{minimal} fashion; as few characters as
96possible will be matched. Using \code{.*?} in the previous
Guido van Rossum0b334101997-12-08 17:33:40 +000097expression will match only \code{<H1>}.
Guido van Rossum1acceb01997-08-14 23:12:18 +000098%
Guido van Rossum0148bbf1997-12-22 22:41:40 +000099\item[\code{\{\var{m},\var{n}\}}] Causes the resulting RE to match from
100\var{m} to \var{n} repetitions of the preceding RE, attempting to
101match as many repetitions as possible. For example, \code{a\{3,5\}}
102will match from 3 to 5 'a' characters.
103%
104\item[\code{\{\var{m},\var{n}\}?}] Causes the resulting RE to
105match from \var{m} to \var{n} repetitions of the preceding RE,
106attempting to match as \emph{few} repetitions as possible. This is
107the non-greedy version of the previous qualifier. For example, on the
1086-character string 'aaaaaa', \code{a\{3,5\}} will match 5 'a'
109characters, while \code{a\{3,5\}?} will only match 3 characters.
110%
Guido van Rossum1acceb01997-08-14 23:12:18 +0000111\item[\code{\e}] Either escapes special characters (permitting you to match
112characters like '*?+\&\$'), or signals a special sequence; special
113sequences are discussed below.
114
115If you're not using a raw string to
116express the pattern, remember that Python also uses the
117backslash as an escape sequence in string literals; if the escape
118sequence isn't recognized by Python's parser, the backslash and
119subsequent character are included in the resulting string. However,
120if Python would recognize the resulting sequence, the backslash should
Fred Drake023f87f1998-01-12 19:16:24 +0000121be repeated twice. This is complicated and hard to understand, so
122it's highly recommended that you use raw strings for all but the
123simplest expressions.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000124%
125\item[\code{[]}] Used to indicate a set of characters. Characters can
Guido van Rossum48d04371997-12-11 20:19:08 +0000126be listed individually, or a range of characters can be indicated by
127giving two characters and separating them by a '-'. Special
128characters are not active inside sets. For example, \code{[akm\$]}
Fred Drake76547c51998-04-03 05:59:05 +0000129will match any of the characters \character{a}, \character{k},
130\character{m}, or \character{\$}; \code{[a-z]}
Guido van Rossum48d04371997-12-11 20:19:08 +0000131will match any lowercase letter and \code{[a-zA-Z0-9]} matches any
132letter or digit. Character classes such as \code{\e w} or \code {\e
133S} (defined below) are also acceptable inside a range. If you want to
Fred Drake20e01961998-02-19 15:09:35 +0000134include a \samp{]} or a \samp{-} inside a set, precede it with a
Guido van Rossum48d04371997-12-11 20:19:08 +0000135backslash.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000136
137Characters \emph{not} within a range can be matched by including a
138\code{\^} as the first character of the set; \code{\^} elsewhere will
Fred Drake20e01961998-02-19 15:09:35 +0000139simply match the \samp{\^} character.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000140%
141\item[\code{|}]\code{A|B}, where A and B can be arbitrary REs,
142creates a regular expression that will match either A or B. This can
Fred Drake20e01961998-02-19 15:09:35 +0000143be used inside groups (see below) as well. To match a literal \samp{|},
Guido van Rossum1acceb01997-08-14 23:12:18 +0000144use \code{\e|}, or enclose it inside a character class, like \code{[|]}.
145%
Guido van Rossum48d04371997-12-11 20:19:08 +0000146\item[\code{(...)}] Matches whatever regular expression is inside the
147parentheses, and indicates the start and end of a group; the contents
148of a group can be retrieved after a match has been performed, and can
149be matched later in the string with the \code{\e \var{number}} special
150sequence, described below. To match the literals '(' or ')',
Guido van Rossum1acceb01997-08-14 23:12:18 +0000151use \code{\e(} or \code{\e)}, or enclose them inside a character
152class: \code{[(] [)]}.
153%
Guido van Rossum0b334101997-12-08 17:33:40 +0000154\item[\code{(?...)}] This is an extension notation (a '?' following a
155'(' is not meaningful otherwise). The first character after the '?'
156determines what the meaning and further syntax of the construct is.
Guido van Rossume9625e81998-04-02 01:32:24 +0000157Extensions usually do not create a new group;
158\code{(?P<\var{name}>...)} is the only exception to this rule.
Guido van Rossum0b334101997-12-08 17:33:40 +0000159Following are the currently supported extensions.
160%
Fred Drake20e01961998-02-19 15:09:35 +0000161\item[\code{(?iLmsx)}] (One or more letters from the set \samp{i},
162\samp{L}, \samp{m}, \samp{s}, \samp{x}.) The group matches
Fred Drake023f87f1998-01-12 19:16:24 +0000163the empty string; the letters set the corresponding flags
Fred Drake20e01961998-02-19 15:09:35 +0000164(\constant{re.I}, \constant{re.L}, \constant{re.M}, \constant{re.S},
165\constant{re.X}) for the entire regular expression. This is useful if
Guido van Rossume9625e81998-04-02 01:32:24 +0000166you wish to include the flags as part of the regular expression, instead
Fred Drake20e01961998-02-19 15:09:35 +0000167of passing a \var{flag} argument to the \function{compile()} function.
Guido van Rossum0b334101997-12-08 17:33:40 +0000168%
Guido van Rossum1acceb01997-08-14 23:12:18 +0000169\item[\code{(?:...)}] A non-grouping version of regular parentheses.
Guido van Rossume9625e81998-04-02 01:32:24 +0000170Matches whatever's inside the parentheses, but the substring matched by the
Guido van Rossum1acceb01997-08-14 23:12:18 +0000171group \emph{cannot} be retrieved after performing a match or
172referenced later in the pattern.
173%
174\item[\code{(?P<\var{name}>...)}] Similar to regular parentheses, but
Guido van Rossume9625e81998-04-02 01:32:24 +0000175the substring matched by the group is accessible via the symbolic group
Guido van Rossum1acceb01997-08-14 23:12:18 +0000176name \var{name}. Group names must be valid Python identifiers. A
177symbolic group is also a numbered group, just as if the group were not
178named. So the group named 'id' in the example above can also be
179referenced as the numbered group 1.
180
Guido van Rossum48d04371997-12-11 20:19:08 +0000181For example, if the pattern is
182\code{(?P<id>[a-zA-Z_]\e w*)}, the group can be referenced by its
Guido van Rossum1acceb01997-08-14 23:12:18 +0000183name in arguments to methods of match objects, such as \code{m.group('id')}
Fred Drake023f87f1998-01-12 19:16:24 +0000184or \code{m.end('id')}, and also by name in pattern text
185(e.g. \code{(?P=id)}) and replacement text (e.g. \code{\e g<id>}).
Guido van Rossum1acceb01997-08-14 23:12:18 +0000186%
Fred Drake023f87f1998-01-12 19:16:24 +0000187\item[\code{(?P=\var{name})}] Matches whatever text was matched by the
188earlier group named \var{name}.
Guido van Rossum48d04371997-12-11 20:19:08 +0000189%
Fred Drake023f87f1998-01-12 19:16:24 +0000190\item[\code{(?\#...)}] A comment; the contents of the parentheses are
191simply ignored.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000192%
Fred Drake023f87f1998-01-12 19:16:24 +0000193\item[\code{(?=...)}] Matches if \code{...} matches next, but doesn't
194consume any of the string. This is called a lookahead assertion. For
195example, \code{Isaac (?=Asimov)} will match 'Isaac~' only if it's
196followed by 'Asimov'.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000197%
Fred Drake023f87f1998-01-12 19:16:24 +0000198\item[\code{(?!...)}] Matches if \code{...} doesn't match next. This
199is a negative lookahead assertion. For example,
200\code{Isaac (?!Asimov)} will match 'Isaac~' only if it's \emph{not}
201followed by 'Asimov'.
Guido van Rossum0b334101997-12-08 17:33:40 +0000202
Fred Drake2705e801998-02-16 21:21:13 +0000203\end{list}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000204
Fred Drake20e01961998-02-19 15:09:35 +0000205The special sequences consist of \samp{\e} and a character from the
Guido van Rossum1acceb01997-08-14 23:12:18 +0000206list below. If the ordinary character is not on the list, then the
207resulting RE will match the second character. For example,
Fred Drake20e01961998-02-19 15:09:35 +0000208\code{\e\$} matches the character \samp{\$}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000209
Fred Drake2705e801998-02-16 21:21:13 +0000210\begin{list}{}{\leftmargin \MyLeftMargin \labelwidth \MyLabelWidth}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000211
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 Rossume9625e81998-04-02 01:32:24 +0000220Inside the \code{[} and \code{]} of a character class, all numeric
221escapes are treated as characters.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000222%
223\item[\code{\e A}] Matches only at the start of the string.
224%
225\item[\code{\e b}] Matches the empty string, but only at the
226beginning or end of a word. A word is defined as a sequence of
227alphanumeric characters, so the end of a word is indicated by
Guido van Rossum48d04371997-12-11 20:19:08 +0000228whitespace or a non-alphanumeric character. Inside a character range,
229\code{\e b} represents the backspace character, for compatibility with
230Python's string literals.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000231%
Guido van Rossum0b334101997-12-08 17:33:40 +0000232\item[\code{\e B}] Matches the empty string, but only when it is
233\emph{not} at the beginning or end of a word.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000234%
235\item[\code{\e d}]Matches any decimal digit; this is
236equivalent to the set \code{[0-9]}.
237%
238\item[\code{\e D}]Matches any non-digit character; this is
Fred Drake20e01961998-02-19 15:09:35 +0000239equivalent to the set \code{[\^0-9]}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000240%
241\item[\code{\e s}]Matches any whitespace character; this is
242equivalent to the set \code{[ \e t\e n\e r\e f\e v]}.
243%
244\item[\code{\e S}]Matches any non-whitespace character; this is
Guido van Rossumf5370f41998-02-11 22:52:47 +0000245equivalent to the set \code{[\^\ \e t\e n\e r\e f\e v]}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000246%
Fred Drake20e01961998-02-19 15:09:35 +0000247\item[\code{\e w}]When the \constant{LOCALE} flag is not specified,
Fred Drake023f87f1998-01-12 19:16:24 +0000248matches any alphanumeric character; this is equivalent to the set
Fred Drake20e01961998-02-19 15:09:35 +0000249\code{[a-zA-Z0-9_]}. With \constant{LOCALE}, it will match the set
Fred Drake023f87f1998-01-12 19:16:24 +0000250\code{[0-9_]} plus whatever characters are defined as letters for the
251current locale.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000252%
Fred Drake20e01961998-02-19 15:09:35 +0000253\item[\code{\e W}]When the \constant{LOCALE} flag is not specified,
Fred Drake023f87f1998-01-12 19:16:24 +0000254matches any non-alphanumeric character; this is equivalent to the set
Fred Drake20e01961998-02-19 15:09:35 +0000255\code{[\^a-zA-Z0-9_]}. With \constant{LOCALE}, it will match any
Fred Drake023f87f1998-01-12 19:16:24 +0000256character not in the set \code{[0-9_]}, and not defined as a letter
Guido van Rossum0b334101997-12-08 17:33:40 +0000257for the current locale.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000258
259\item[\code{\e Z}]Matches only at the end of the string.
260%
261
262\item[\code{\e \e}] Matches a literal backslash.
263
Fred Drake2705e801998-02-16 21:21:13 +0000264\end{list}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000265
266\subsection{Module Contents}
Fred Drake78f8e981997-12-29 21:39:39 +0000267\nodename{Contents of Module re}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000268
269The module defines the following functions and constants, and an exception:
270
Guido van Rossum1acceb01997-08-14 23:12:18 +0000271
Fred Drake013ad981998-03-08 07:38:27 +0000272\begin{funcdesc}{compile}{pattern\optional{, flags}}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000273 Compile a regular expression pattern into a regular expression
Fred Drake20e01961998-02-19 15:09:35 +0000274 object, which can be used for matching using its \function{match()} and
275 \function{search()} methods, described below.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000276
Guido van Rossum0b334101997-12-08 17:33:40 +0000277 The expression's behaviour can be modified by specifying a
278 \var{flags} value. Values can be any of the following variables,
279 combined using bitwise OR (the \code{|} operator).
280
Fred Drake76547c51998-04-03 05:59:05 +0000281The sequence
282
283\begin{verbatim}
284prog = re.compile(pat)
285result = prog.match(str)
286\end{verbatim}
287
288is equivalent to
289
290\begin{verbatim}
291result = re.match(pat, str)
292\end{verbatim}
293
294but the version using \function{compile()} is more efficient when the
295expression will be used several times in a single program.
296%(The compiled version of the last pattern passed to
297%\function{regex.match()} or \function{regex.search()} is cached, so
298%programs that use only a single regular expression at a time needn't
299%worry about compiling regular expressions.)
300\end{funcdesc}
301
Fred Drake013ad981998-03-08 07:38:27 +0000302\begin{datadesc}{I}
303\dataline{IGNORECASE}
Fred Drake78f8e981997-12-29 21:39:39 +0000304Perform case-insensitive matching; expressions like \code{[A-Z]} will match
Guido van Rossum48d04371997-12-11 20:19:08 +0000305lowercase letters, too. This is not affected by the current locale.
Fred Drake013ad981998-03-08 07:38:27 +0000306\end{datadesc}
Guido van Rossum0b334101997-12-08 17:33:40 +0000307
Fred Drake013ad981998-03-08 07:38:27 +0000308\begin{datadesc}{L}
309\dataline{LOCALE}
Fred Drake78f8e981997-12-29 21:39:39 +0000310Make \code{\e w}, \code{\e W}, \code{\e b},
Guido van Rossum48d04371997-12-11 20:19:08 +0000311\code{\e B}, dependent on the current locale.
Fred Drake013ad981998-03-08 07:38:27 +0000312\end{datadesc}
Guido van Rossuma42c1781997-12-09 20:41:47 +0000313
Fred Drake013ad981998-03-08 07:38:27 +0000314\begin{datadesc}{M}
315\dataline{MULTILINE}
Fred Drake78f8e981997-12-29 21:39:39 +0000316When specified, the pattern character \code{\^} matches at the
Fred Drake023f87f1998-01-12 19:16:24 +0000317beginning of the string and at the beginning of each line
318(immediately following each newline); and the pattern character
Guido van Rossum48d04371997-12-11 20:19:08 +0000319\code{\$} matches at the end of the string and at the end of each line
320(immediately preceding each newline).
Guido van Rossum0b334101997-12-08 17:33:40 +0000321By default, \code{\^} matches only at the beginning of the string, and
322\code{\$} only at the end of the string and immediately before the
323newline (if any) at the end of the string.
Fred Drake013ad981998-03-08 07:38:27 +0000324\end{datadesc}
Guido van Rossum0b334101997-12-08 17:33:40 +0000325
Fred Drake013ad981998-03-08 07:38:27 +0000326\begin{datadesc}{S}
327\dataline{DOTALL}
Guido van Rossume9625e81998-04-02 01:32:24 +0000328Make the \code{.} special character match any character at all, including a
Guido van Rossum48d04371997-12-11 20:19:08 +0000329newline; without this flag, \code{.} will match anything \emph{except}
Fred Drake78f8e981997-12-29 21:39:39 +0000330a newline.
Fred Drake013ad981998-03-08 07:38:27 +0000331\end{datadesc}
Guido van Rossum48d04371997-12-11 20:19:08 +0000332
Fred Drake013ad981998-03-08 07:38:27 +0000333\begin{datadesc}{X}
334\dataline{VERBOSE}
Fred Drake78f8e981997-12-29 21:39:39 +0000335Ignore whitespace within the pattern
Guido van Rossum48d04371997-12-11 20:19:08 +0000336except when in a character class or preceded by an unescaped
337backslash, and, when a line contains a \code{\#} neither in a character
338class or preceded by an unescaped backslash, all characters from the
Fred Drake78f8e981997-12-29 21:39:39 +0000339leftmost such \code{\#} through the end of the line are ignored.
Fred Drake013ad981998-03-08 07:38:27 +0000340\end{datadesc}
Guido van Rossum0b334101997-12-08 17:33:40 +0000341
Guido van Rossum0b334101997-12-08 17:33:40 +0000342
Guido van Rossum1acceb01997-08-14 23:12:18 +0000343\begin{funcdesc}{escape}{string}
Guido van Rossum48d04371997-12-11 20:19:08 +0000344 Return \var{string} with all non-alphanumerics backslashed; this is
345 useful if you want to match an arbitrary literal string that may have
346 regular expression metacharacters in it.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000347\end{funcdesc}
348
Fred Drake013ad981998-03-08 07:38:27 +0000349\begin{funcdesc}{match}{pattern, string\optional{, flags}}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000350 If zero or more characters at the beginning of \var{string} match
351 the regular expression \var{pattern}, return a corresponding
Fred Drake20e01961998-02-19 15:09:35 +0000352 \class{MatchObject} instance. Return \code{None} if the string does not
Guido van Rossum1acceb01997-08-14 23:12:18 +0000353 match the pattern; note that this is different from a zero-length
354 match.
355\end{funcdesc}
356
Fred Drake013ad981998-03-08 07:38:27 +0000357\begin{funcdesc}{search}{pattern, string\optional{, flags}}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000358 Scan through \var{string} looking for a location where the regular
Fred Drake023f87f1998-01-12 19:16:24 +0000359 expression \var{pattern} produces a match, and return a
Fred Drake20e01961998-02-19 15:09:35 +0000360 corresponding \class{MatchObject} instance.
Guido van Rossum0148bbf1997-12-22 22:41:40 +0000361 Return \code{None} if no
Guido van Rossum1acceb01997-08-14 23:12:18 +0000362 position in the string matches the pattern; note that this is
363 different from finding a zero-length match at some point in the string.
364\end{funcdesc}
365
Fred Drake013ad981998-03-08 07:38:27 +0000366\begin{funcdesc}{split}{pattern, string, \optional{, maxsplit\code{ = 0}}}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000367 Split \var{string} by the occurrences of \var{pattern}. If
368 capturing parentheses are used in pattern, then occurrences of
369 patterns or subpatterns are also returned.
Guido van Rossum97546391998-01-12 18:58:53 +0000370 If \var{maxsplit} is nonzero, at most \var{maxsplit} splits
371 occur, and the remainder of the string is returned as the final
372 element of the list. (Incompatibility note: in the original Python
373 1.5 release, \var{maxsplit} was ignored. This has been fixed in
374 later releases.)
Guido van Rossum1acceb01997-08-14 23:12:18 +0000375%
Fred Drake19479911998-02-13 06:58:54 +0000376\begin{verbatim}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000377>>> re.split('[\W]+', 'Words, words, words.')
378['Words', 'words', 'words', '']
379>>> re.split('([\W]+)', 'Words, words, words.')
380['Words', ', ', 'words', ', ', 'words', '.', '']
Guido van Rossum97546391998-01-12 18:58:53 +0000381>>> re.split('[\W]+', 'Words, words, words.', 1)
382['Words', 'words, words.']
Fred Drake19479911998-02-13 06:58:54 +0000383\end{verbatim}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000384%
385 This function combines and extends the functionality of
Fred Drake20e01961998-02-19 15:09:35 +0000386 the old \function{regsub.split()} and \function{regsub.splitx()}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000387\end{funcdesc}
388
Fred Drake013ad981998-03-08 07:38:27 +0000389\begin{funcdesc}{sub}{pattern, repl, string\optional{, count\code{ = 0}}}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000390Return the string obtained by replacing the leftmost non-overlapping
391occurrences of \var{pattern} in \var{string} by the replacement
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000392\var{repl}. If the pattern isn't found, \var{string} is returned
393unchanged. \var{repl} can be a string or a function; if a function,
394it is called for every non-overlapping occurance of \var{pattern}.
Guido van Rossum0b334101997-12-08 17:33:40 +0000395The function takes a single match object argument, and returns the
396replacement string. For example:
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000397%
Fred Drake19479911998-02-13 06:58:54 +0000398\begin{verbatim}
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000399>>> def dashrepl(matchobj):
Guido van Rossume9625e81998-04-02 01:32:24 +0000400.... if matchobj.group(0) == '-': return ' '
401.... else: return '-'
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000402>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
403'pro--gram files'
Fred Drake19479911998-02-13 06:58:54 +0000404\end{verbatim}
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000405%
Guido van Rossum0b334101997-12-08 17:33:40 +0000406The pattern may be a string or a
Guido van Rossum48d04371997-12-11 20:19:08 +0000407regex object; if you need to specify
408regular expression flags, you must use a regex object, or use
409embedded modifiers in a pattern; e.g.
Fred Drake013ad981998-03-08 07:38:27 +0000410\samp{sub("(?i)b+", "x", "bbbb BBBB")} returns \code{'x x'}.
Fred Drake023f87f1998-01-12 19:16:24 +0000411
Guido van Rossum1acceb01997-08-14 23:12:18 +0000412The optional argument \var{count} is the maximum number of pattern
413occurrences to be replaced; count must be a non-negative integer, and
414the default value of 0 means to replace all occurrences.
415
416Empty matches for the pattern are replaced only when not adjacent to a
Fred Drake013ad981998-03-08 07:38:27 +0000417previous match, so \samp{sub('x*', '-', 'abc')} returns \code{'-a-b-c-'}.
Guido van Rossume9625e81998-04-02 01:32:24 +0000418
419If \var{repl} is a string, any backslash escapes in it are processed.
420That is, \samp{\e n} is converted to a single newline character,
421\samp{\e r} is converted to a linefeed, and so forth. Unknown escapes
Guido van Rossum791468f1998-04-03 20:07:37 +0000422such as \samp{\e j} are left alone. Backreferences, such as \samp{\e 6} are
Guido van Rossume9625e81998-04-02 01:32:24 +0000423replaced with the substring matched by group 6 in the pattern.
424
425In addition to character escapes and backreferences as described
426above, \samp{\e g<name>} will use the substring matched by the group
427named \samp{name}, as defined by the \samp{(?P<name>...)} syntax.
428\samp{\e g<number>} uses the corresponding group number; \samp{\e
429g<2>} is therefore equivalent to \samp{\e 2}, but isn't ambiguous in a
430replacement such as \samp{\e g<2>0}. \samp{\e 20} would be
431interpreted as a reference to group 20, not a reference to group 2
432followed by the literal character \samp{0}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000433\end{funcdesc}
434
Fred Drake013ad981998-03-08 07:38:27 +0000435\begin{funcdesc}{subn}{pattern, repl, string\optional{, count\code{ = 0}}}
Fred Drake20e01961998-02-19 15:09:35 +0000436Perform the same operation as \function{sub()}, but return a tuple
Fred Drake023f87f1998-01-12 19:16:24 +0000437\code{(\var{new_string}, \var{number_of_subs_made})}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000438\end{funcdesc}
439
440\begin{excdesc}{error}
441 Exception raised when a string passed to one of the functions here
442 is not a valid regular expression (e.g., unmatched parentheses) or
Fred Drake013ad981998-03-08 07:38:27 +0000443 when some other error occurs during compilation or matching. It is
444 never an error if a string contains no match for a pattern.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000445\end{excdesc}
446
447\subsection{Regular Expression Objects}
448Compiled regular expression objects support the following methods and
449attributes:
450
Fred Drake76547c51998-04-03 05:59:05 +0000451\begin{methoddesc}[RegexObject]{match}{string\optional{, pos}\optional{,
452 endpos}}
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000453 If zero or more characters at the beginning of \var{string} match
454 this regular expression, return a corresponding
Fred Drake20e01961998-02-19 15:09:35 +0000455 \class{MatchObject} instance. Return \code{None} if the string does not
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000456 match the pattern; note that this is different from a zero-length
457 match.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000458
459 The optional second parameter \var{pos} gives an index in the string
Guido van Rossum48d04371997-12-11 20:19:08 +0000460 where the search is to start; it defaults to \code{0}. The
Fred Drake20e01961998-02-19 15:09:35 +0000461 \samp{\^} pattern character will match at the index where the
Guido van Rossum48d04371997-12-11 20:19:08 +0000462 search is to start.
Guido van Rossum0b334101997-12-08 17:33:40 +0000463
464 The optional parameter \var{endpos} limits how far the string will
465 be searched; it will be as if the string is \var{endpos} characters
466 long, so only the characters from \var{pos} to \var{endpos} will be
467 searched for a match.
Fred Drake76547c51998-04-03 05:59:05 +0000468\end{methoddesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000469
Fred Drake76547c51998-04-03 05:59:05 +0000470\begin{methoddesc}[RegexObject]{search}{string\optional{, pos}\optional{,
471 endpos}}
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000472 Scan through \var{string} looking for a location where this regular
473 expression produces a match. Return \code{None} if no
474 position in the string matches the pattern; note that this is
475 different from finding a zero-length match at some point in the string.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000476
Guido van Rossum48d04371997-12-11 20:19:08 +0000477 The optional \var{pos} and \var{endpos} parameters have the same
Fred Drake20e01961998-02-19 15:09:35 +0000478 meaning as for the \method{match()} method.
Fred Drake76547c51998-04-03 05:59:05 +0000479\end{methoddesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000480
Fred Drake76547c51998-04-03 05:59:05 +0000481\begin{methoddesc}[RegexObject]{split}{string, \optional{,
482 maxsplit\code{ = 0}}}
Fred Drake20e01961998-02-19 15:09:35 +0000483Identical to the \function{split()} function, using the compiled pattern.
Fred Drake76547c51998-04-03 05:59:05 +0000484\end{methoddesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000485
Fred Drake76547c51998-04-03 05:59:05 +0000486\begin{methoddesc}[RegexObject]{sub}{repl, string\optional{, count\code{ = 0}}}
Fred Drake20e01961998-02-19 15:09:35 +0000487Identical to the \function{sub()} function, using the compiled pattern.
Fred Drake76547c51998-04-03 05:59:05 +0000488\end{methoddesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000489
Fred Drake76547c51998-04-03 05:59:05 +0000490\begin{methoddesc}[RegexObject]{subn}{repl, string\optional{,
491 count\code{ = 0}}}
Fred Drake20e01961998-02-19 15:09:35 +0000492Identical to the \function{subn()} function, using the compiled pattern.
Fred Drake76547c51998-04-03 05:59:05 +0000493\end{methoddesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000494
Guido van Rossum1acceb01997-08-14 23:12:18 +0000495
Fred Drake76547c51998-04-03 05:59:05 +0000496\begin{memberdesc}[RegexObject]{flags}
Fred Drake013ad981998-03-08 07:38:27 +0000497The flags argument used when the regex object was compiled, or
498\code{0} if no flags were provided.
Fred Drake76547c51998-04-03 05:59:05 +0000499\end{memberdesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000500
Fred Drake76547c51998-04-03 05:59:05 +0000501\begin{memberdesc}[RegexObject]{groupindex}
Fred Drake013ad981998-03-08 07:38:27 +0000502A dictionary mapping any symbolic group names defined by
503\code{(?P<\var{id}>)} to group numbers. The dictionary is empty if no
Guido van Rossum1acceb01997-08-14 23:12:18 +0000504symbolic groups were used in the pattern.
Fred Drake76547c51998-04-03 05:59:05 +0000505\end{memberdesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000506
Fred Drake76547c51998-04-03 05:59:05 +0000507\begin{memberdesc}[RegexObject]{pattern}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000508The pattern string from which the regex object was compiled.
Fred Drake76547c51998-04-03 05:59:05 +0000509\end{memberdesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000510
Fred Drake023f87f1998-01-12 19:16:24 +0000511\subsection{Match Objects}
512
Fred Drake20e01961998-02-19 15:09:35 +0000513\class{MatchObject} instances support the following methods and attributes:
Guido van Rossum1acceb01997-08-14 23:12:18 +0000514
Fred Drake76547c51998-04-03 05:59:05 +0000515\begin{methoddesc}[MatchObject]{group}{\optional{group1, group2, ...}}
Guido van Rossum46503921998-01-19 23:14:17 +0000516Returns one or more subgroups of the match. If there is a single
517argument, the result is a single string; if there are
Guido van Rossum48d04371997-12-11 20:19:08 +0000518multiple arguments, the result is a tuple with one item per argument.
Guido van Rossum46503921998-01-19 23:14:17 +0000519Without arguments, \var{group1} defaults to zero (i.e. the whole match
520is returned).
521If a \var{groupN} argument is zero, the corresponding return value is the
Guido van Rossum48d04371997-12-11 20:19:08 +0000522entire matching string; if it is in the inclusive range [1..99], it is
Guido van Rossum791468f1998-04-03 20:07:37 +0000523the string matching the the corresponding parenthesized group. If a
524group number is negative or larger than the number of groups defined
525in the pattern, an \exception{IndexError} exception is raised.
526If a group is contained in a part of the pattern that did not match,
527the corresponding result is \code{None}. If a group is contained in a
528part of the pattern that matched multiple times, the last match is
529returned.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000530
Guido van Rossum0b334101997-12-08 17:33:40 +0000531If the regular expression uses the \code{(?P<\var{name}>...)} syntax,
Guido van Rossum46503921998-01-19 23:14:17 +0000532the \var{groupN} arguments may also be strings identifying groups by
Guido van Rossum791468f1998-04-03 20:07:37 +0000533their group name. If a string argument is not used as a group name in
534the pattern, an \exception{IndexError} exception is raised.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000535
536A moderately complicated example:
Fred Drake023f87f1998-01-12 19:16:24 +0000537
538\begin{verbatim}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000539m = re.match(r"(?P<int>\d+)\.(\d*)", '3.14')
Fred Drake023f87f1998-01-12 19:16:24 +0000540\end{verbatim}
541
542After performing this match, \code{m.group(1)} is \code{'3'}, as is
Guido van Rossum46503921998-01-19 23:14:17 +0000543\code{m.group('int')}, and \code{m.group(2)} is \code{'14'}.
Fred Drake76547c51998-04-03 05:59:05 +0000544\end{methoddesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000545
Fred Drake76547c51998-04-03 05:59:05 +0000546\begin{methoddesc}[MatchObject]{groups}{}
Guido van Rossum48d04371997-12-11 20:19:08 +0000547Return a tuple containing all the subgroups of the match, from 1 up to
548however many groups are in the pattern. Groups that did not
Guido van Rossum97546391998-01-12 18:58:53 +0000549participate in the match have values of \code{None}. (Incompatibility
550note: in the original Python 1.5 release, if the tuple was one element
551long, a string would be returned instead. In later versions, a
552singleton tuple is returned in such cases.)
Fred Drake76547c51998-04-03 05:59:05 +0000553\end{methoddesc}
Guido van Rossum48d04371997-12-11 20:19:08 +0000554
Fred Drake76547c51998-04-03 05:59:05 +0000555\begin{methoddesc}[MatchObject]{start}{\optional{group}}
Fred Drake013ad981998-03-08 07:38:27 +0000556\funcline{end}{\optional{group}}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000557Return the indices of the start and end of the substring
Guido van Rossum46503921998-01-19 23:14:17 +0000558matched by \var{group}; \var{group} defaults to zero (meaning the whole
559matched substring).
560Return \code{None} if \var{group} exists but
Guido van Rossume4eb2231997-12-17 00:23:39 +0000561did not contribute to the match. For a match object
Fred Drake023f87f1998-01-12 19:16:24 +0000562\var{m}, and a group \var{g} that did contribute to the match, the
563substring matched by group \var{g} (equivalent to
564\code{\var{m}.group(\var{g})}) is
565
566\begin{verbatim}
567m.string[m.start(g):m.end(g)]
568\end{verbatim}
569
Guido van Rossume4eb2231997-12-17 00:23:39 +0000570Note that
571\code{m.start(\var{group})} will equal \code{m.end(\var{group})} if
Fred Drake023f87f1998-01-12 19:16:24 +0000572\var{group} matched a null string. For example, after \code{\var{m} =
573re.search('b(c?)', 'cba')}, \code{\var{m}.start(0)} is 1,
574\code{\var{m}.end(0)} is 2, \code{\var{m}.start(1)} and
575\code{\var{m}.end(1)} are both 2, and \code{\var{m}.start(2)} raises
Fred Drake20e01961998-02-19 15:09:35 +0000576an \exception{IndexError} exception.
Fred Drake76547c51998-04-03 05:59:05 +0000577\end{methoddesc}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000578
Fred Drake76547c51998-04-03 05:59:05 +0000579\begin{methoddesc}[MatchObject]{span}{\optional{group}}
Fred Drake20e01961998-02-19 15:09:35 +0000580For \class{MatchObject} \var{m}, return the 2-tuple
Fred Drake023f87f1998-01-12 19:16:24 +0000581\code{(\var{m}.start(\var{group}), \var{m}.end(\var{group}))}.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000582Note that if \var{group} did not contribute to the match, this is
Guido van Rossum46503921998-01-19 23:14:17 +0000583\code{(None, None)}. Again, \var{group} defaults to zero.
Fred Drake76547c51998-04-03 05:59:05 +0000584\end{methoddesc}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000585
Fred Drake76547c51998-04-03 05:59:05 +0000586\begin{memberdesc}[MatchObject]{pos}
Guido van Rossum0b334101997-12-08 17:33:40 +0000587The value of \var{pos} which was passed to the
Fred Drake20e01961998-02-19 15:09:35 +0000588\function{search()} or \function{match()} function. This is the index into
Fred Drake023f87f1998-01-12 19:16:24 +0000589the string at which the regex engine started looking for a match.
Fred Drake76547c51998-04-03 05:59:05 +0000590\end{memberdesc}
Guido van Rossum0b334101997-12-08 17:33:40 +0000591
Fred Drake76547c51998-04-03 05:59:05 +0000592\begin{memberdesc}[MatchObject]{endpos}
Guido van Rossum0b334101997-12-08 17:33:40 +0000593The value of \var{endpos} which was passed to the
Fred Drake20e01961998-02-19 15:09:35 +0000594\function{search()} or \function{match()} function. This is the index into
Fred Drake023f87f1998-01-12 19:16:24 +0000595the string beyond which the regex engine will not go.
Fred Drake76547c51998-04-03 05:59:05 +0000596\end{memberdesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000597
Fred Drake76547c51998-04-03 05:59:05 +0000598\begin{memberdesc}[MatchObject]{re}
Fred Drake20e01961998-02-19 15:09:35 +0000599The regular expression object whose \method{match()} or
600\method{search()} method produced this \class{MatchObject} instance.
Fred Drake76547c51998-04-03 05:59:05 +0000601\end{memberdesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000602
Fred Drake76547c51998-04-03 05:59:05 +0000603\begin{memberdesc}[MatchObject]{string}
Fred Drake20e01961998-02-19 15:09:35 +0000604The string passed to \function{match()} or \function{search()}.
Fred Drake76547c51998-04-03 05:59:05 +0000605\end{memberdesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000606
Guido van Rossum1acceb01997-08-14 23:12:18 +0000607\begin{seealso}
Fred Drakef9951811997-12-29 16:37:04 +0000608\seetext{Jeffrey Friedl, \emph{Mastering Regular Expressions},
Fred Drake023f87f1998-01-12 19:16:24 +0000609O'Reilly. The Python material in this book dates from before the
Fred Drake20e01961998-02-19 15:09:35 +0000610\module{re} module, but it covers writing good regular expression
Fred Drake023f87f1998-01-12 19:16:24 +0000611patterns in great detail.}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000612\end{seealso}