blob: 85471e5c95df8fbd5c5a0801f5da9432fb961411 [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
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\$]}
129will match any of the characters 'a', 'k', 'm', or '\$'; \code{[a-z]}
130will match any lowercase letter and \code{[a-zA-Z0-9]} matches any
131letter or digit. Character classes such as \code{\e w} or \code {\e
132S} (defined below) are also acceptable inside a range. If you want to
Fred Drake20e01961998-02-19 15:09:35 +0000133include a \samp{]} or a \samp{-} inside a set, precede it with a
Guido van Rossum48d04371997-12-11 20:19:08 +0000134backslash.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000135
136Characters \emph{not} within a range can be matched by including a
137\code{\^} as the first character of the set; \code{\^} elsewhere will
Fred Drake20e01961998-02-19 15:09:35 +0000138simply match the \samp{\^} character.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000139%
140\item[\code{|}]\code{A|B}, where A and B can be arbitrary REs,
141creates a regular expression that will match either A or B. This can
Fred Drake20e01961998-02-19 15:09:35 +0000142be used inside groups (see below) as well. To match a literal \samp{|},
Guido van Rossum1acceb01997-08-14 23:12:18 +0000143use \code{\e|}, or enclose it inside a character class, like \code{[|]}.
144%
Guido van Rossum48d04371997-12-11 20:19:08 +0000145\item[\code{(...)}] Matches whatever regular expression is inside the
146parentheses, and indicates the start and end of a group; the contents
147of a group can be retrieved after a match has been performed, and can
148be matched later in the string with the \code{\e \var{number}} special
149sequence, described below. To match the literals '(' or ')',
Guido van Rossum1acceb01997-08-14 23:12:18 +0000150use \code{\e(} or \code{\e)}, or enclose them inside a character
151class: \code{[(] [)]}.
152%
Guido van Rossum0b334101997-12-08 17:33:40 +0000153\item[\code{(?...)}] This is an extension notation (a '?' following a
154'(' is not meaningful otherwise). The first character after the '?'
155determines what the meaning and further syntax of the construct is.
156Following are the currently supported extensions.
157%
Fred Drake20e01961998-02-19 15:09:35 +0000158\item[\code{(?iLmsx)}] (One or more letters from the set \samp{i},
159\samp{L}, \samp{m}, \samp{s}, \samp{x}.) The group matches
Fred Drake023f87f1998-01-12 19:16:24 +0000160the empty string; the letters set the corresponding flags
Fred Drake20e01961998-02-19 15:09:35 +0000161(\constant{re.I}, \constant{re.L}, \constant{re.M}, \constant{re.S},
162\constant{re.X}) for the entire regular expression. This is useful if
163you wish include the flags as part of the regular expression, instead
164of passing a \var{flag} argument to the \function{compile()} function.
Guido van Rossum0b334101997-12-08 17:33:40 +0000165%
Guido van Rossum1acceb01997-08-14 23:12:18 +0000166\item[\code{(?:...)}] A non-grouping version of regular parentheses.
167Matches whatever's inside the parentheses, but the text matched by the
168group \emph{cannot} be retrieved after performing a match or
169referenced later in the pattern.
170%
171\item[\code{(?P<\var{name}>...)}] Similar to regular parentheses, but
172the text matched by the group is accessible via the symbolic group
173name \var{name}. Group names must be valid Python identifiers. A
174symbolic group is also a numbered group, just as if the group were not
175named. So the group named 'id' in the example above can also be
176referenced as the numbered group 1.
177
Guido van Rossum48d04371997-12-11 20:19:08 +0000178For example, if the pattern is
179\code{(?P<id>[a-zA-Z_]\e w*)}, the group can be referenced by its
Guido van Rossum1acceb01997-08-14 23:12:18 +0000180name in arguments to methods of match objects, such as \code{m.group('id')}
Fred Drake023f87f1998-01-12 19:16:24 +0000181or \code{m.end('id')}, and also by name in pattern text
182(e.g. \code{(?P=id)}) and replacement text (e.g. \code{\e g<id>}).
Guido van Rossum1acceb01997-08-14 23:12:18 +0000183%
Fred Drake023f87f1998-01-12 19:16:24 +0000184\item[\code{(?P=\var{name})}] Matches whatever text was matched by the
185earlier group named \var{name}.
Guido van Rossum48d04371997-12-11 20:19:08 +0000186%
Fred Drake023f87f1998-01-12 19:16:24 +0000187\item[\code{(?\#...)}] A comment; the contents of the parentheses are
188simply ignored.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000189%
Fred Drake023f87f1998-01-12 19:16:24 +0000190\item[\code{(?=...)}] Matches if \code{...} matches next, but doesn't
191consume any of the string. This is called a lookahead assertion. For
192example, \code{Isaac (?=Asimov)} will match 'Isaac~' only if it's
193followed by 'Asimov'.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000194%
Fred Drake023f87f1998-01-12 19:16:24 +0000195\item[\code{(?!...)}] Matches if \code{...} doesn't match next. This
196is a negative lookahead assertion. For example,
197\code{Isaac (?!Asimov)} will match 'Isaac~' only if it's \emph{not}
198followed by 'Asimov'.
Guido van Rossum0b334101997-12-08 17:33:40 +0000199
Fred Drake2705e801998-02-16 21:21:13 +0000200\end{list}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000201
Fred Drake20e01961998-02-19 15:09:35 +0000202The special sequences consist of \samp{\e} and a character from the
Guido van Rossum1acceb01997-08-14 23:12:18 +0000203list below. If the ordinary character is not on the list, then the
204resulting RE will match the second character. For example,
Fred Drake20e01961998-02-19 15:09:35 +0000205\code{\e\$} matches the character \samp{\$}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000206
Fred Drake2705e801998-02-16 21:21:13 +0000207\begin{list}{}{\leftmargin \MyLeftMargin \labelwidth \MyLabelWidth}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000208
209%
210\item[\code{\e \var{number}}] Matches the contents of the group of the
Guido van Rossum0b334101997-12-08 17:33:40 +0000211same number. Groups are numbered starting from 1. For example,
212\code{(.+) \e 1} matches 'the the' or '55 55', but not 'the end' (note
213the space after the group). This special sequence can only be used to
214match one of the first 99 groups. If the first digit of \var{number}
215is 0, or \var{number} is 3 octal digits long, it will not be interpreted
216as a group match, but as the character with octal value \var{number}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000217%
218\item[\code{\e A}] Matches only at the start of the string.
219%
220\item[\code{\e b}] Matches the empty string, but only at the
221beginning or end of a word. A word is defined as a sequence of
222alphanumeric characters, so the end of a word is indicated by
Guido van Rossum48d04371997-12-11 20:19:08 +0000223whitespace or a non-alphanumeric character. Inside a character range,
224\code{\e b} represents the backspace character, for compatibility with
225Python's string literals.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000226%
Guido van Rossum0b334101997-12-08 17:33:40 +0000227\item[\code{\e B}] Matches the empty string, but only when it is
228\emph{not} at the beginning or end of a word.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000229%
230\item[\code{\e d}]Matches any decimal digit; this is
231equivalent to the set \code{[0-9]}.
232%
233\item[\code{\e D}]Matches any non-digit character; this is
Fred Drake20e01961998-02-19 15:09:35 +0000234equivalent to the set \code{[\^0-9]}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000235%
236\item[\code{\e s}]Matches any whitespace character; this is
237equivalent to the set \code{[ \e t\e n\e r\e f\e v]}.
238%
239\item[\code{\e S}]Matches any non-whitespace character; this is
Guido van Rossumf5370f41998-02-11 22:52:47 +0000240equivalent to the set \code{[\^\ \e t\e n\e r\e f\e v]}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000241%
Fred Drake20e01961998-02-19 15:09:35 +0000242\item[\code{\e w}]When the \constant{LOCALE} flag is not specified,
Fred Drake023f87f1998-01-12 19:16:24 +0000243matches any alphanumeric character; this is equivalent to the set
Fred Drake20e01961998-02-19 15:09:35 +0000244\code{[a-zA-Z0-9_]}. With \constant{LOCALE}, it will match the set
Fred Drake023f87f1998-01-12 19:16:24 +0000245\code{[0-9_]} plus whatever characters are defined as letters for the
246current locale.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000247%
Fred Drake20e01961998-02-19 15:09:35 +0000248\item[\code{\e W}]When the \constant{LOCALE} flag is not specified,
Fred Drake023f87f1998-01-12 19:16:24 +0000249matches any non-alphanumeric character; this is equivalent to the set
Fred Drake20e01961998-02-19 15:09:35 +0000250\code{[\^a-zA-Z0-9_]}. With \constant{LOCALE}, it will match any
Fred Drake023f87f1998-01-12 19:16:24 +0000251character not in the set \code{[0-9_]}, and not defined as a letter
Guido van Rossum0b334101997-12-08 17:33:40 +0000252for the current locale.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000253
254\item[\code{\e Z}]Matches only at the end of the string.
255%
256
257\item[\code{\e \e}] Matches a literal backslash.
258
Fred Drake2705e801998-02-16 21:21:13 +0000259\end{list}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000260
261\subsection{Module Contents}
Fred Drake78f8e981997-12-29 21:39:39 +0000262\nodename{Contents of Module re}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000263
264The module defines the following functions and constants, and an exception:
265
Fred Drake19479911998-02-13 06:58:54 +0000266\setindexsubitem{(in module re)}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000267
Fred Drake013ad981998-03-08 07:38:27 +0000268\begin{funcdesc}{compile}{pattern\optional{, flags}}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000269 Compile a regular expression pattern into a regular expression
Fred Drake20e01961998-02-19 15:09:35 +0000270 object, which can be used for matching using its \function{match()} and
271 \function{search()} methods, described below.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000272
Guido van Rossum0b334101997-12-08 17:33:40 +0000273 The expression's behaviour can be modified by specifying a
274 \var{flags} value. Values can be any of the following variables,
275 combined using bitwise OR (the \code{|} operator).
276
Fred Drake013ad981998-03-08 07:38:27 +0000277\begin{datadesc}{I}
278\dataline{IGNORECASE}
Fred Drake78f8e981997-12-29 21:39:39 +0000279Perform 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.
Fred Drake013ad981998-03-08 07:38:27 +0000281\end{datadesc}
Guido van Rossum0b334101997-12-08 17:33:40 +0000282
Fred Drake013ad981998-03-08 07:38:27 +0000283\begin{datadesc}{L}
284\dataline{LOCALE}
Fred Drake78f8e981997-12-29 21:39:39 +0000285Make \code{\e w}, \code{\e W}, \code{\e b},
Guido van Rossum48d04371997-12-11 20:19:08 +0000286\code{\e B}, dependent on the current locale.
Fred Drake013ad981998-03-08 07:38:27 +0000287\end{datadesc}
Guido van Rossuma42c1781997-12-09 20:41:47 +0000288
Fred Drake013ad981998-03-08 07:38:27 +0000289\begin{datadesc}{M}
290\dataline{MULTILINE}
Fred Drake78f8e981997-12-29 21:39:39 +0000291When specified, the pattern character \code{\^} matches at the
Fred Drake023f87f1998-01-12 19:16:24 +0000292beginning of the string and at the beginning of each line
293(immediately following each newline); and the pattern character
Guido van Rossum48d04371997-12-11 20:19:08 +0000294\code{\$} matches at the end of the string and at the end of each line
295(immediately preceding each newline).
Guido van Rossum0b334101997-12-08 17:33:40 +0000296By default, \code{\^} matches only at the beginning of the string, and
297\code{\$} only at the end of the string and immediately before the
298newline (if any) at the end of the string.
Fred Drake013ad981998-03-08 07:38:27 +0000299\end{datadesc}
Guido van Rossum0b334101997-12-08 17:33:40 +0000300
Fred Drake013ad981998-03-08 07:38:27 +0000301\begin{datadesc}{S}
302\dataline{DOTALL}
Fred Drake78f8e981997-12-29 21:39:39 +0000303Make the \code{.} special character any character at all, including a
Guido van Rossum48d04371997-12-11 20:19:08 +0000304newline; without this flag, \code{.} will match anything \emph{except}
Fred Drake78f8e981997-12-29 21:39:39 +0000305a newline.
Fred Drake013ad981998-03-08 07:38:27 +0000306\end{datadesc}
Guido van Rossum48d04371997-12-11 20:19:08 +0000307
Fred Drake013ad981998-03-08 07:38:27 +0000308\begin{datadesc}{X}
309\dataline{VERBOSE}
Fred Drake78f8e981997-12-29 21:39:39 +0000310Ignore whitespace within the pattern
Guido van Rossum48d04371997-12-11 20:19:08 +0000311except when in a character class or preceded by an unescaped
312backslash, and, when a line contains a \code{\#} neither in a character
313class or preceded by an unescaped backslash, all characters from the
Fred Drake78f8e981997-12-29 21:39:39 +0000314leftmost such \code{\#} through the end of the line are ignored.
Fred Drake013ad981998-03-08 07:38:27 +0000315\end{datadesc}
Guido van Rossum0b334101997-12-08 17:33:40 +0000316
Guido van Rossum0b334101997-12-08 17:33:40 +0000317
Fred Drake78f8e981997-12-29 21:39:39 +0000318The sequence
Fred Drake013ad981998-03-08 07:38:27 +0000319
Fred Drake19479911998-02-13 06:58:54 +0000320\begin{verbatim}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000321prog = re.compile(pat)
322result = prog.match(str)
Fred Drake19479911998-02-13 06:58:54 +0000323\end{verbatim}
Fred Drake013ad981998-03-08 07:38:27 +0000324
Guido van Rossum1acceb01997-08-14 23:12:18 +0000325is equivalent to
Fred Drake023f87f1998-01-12 19:16:24 +0000326
327\begin{verbatim}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000328result = re.match(pat, str)
Fred Drake023f87f1998-01-12 19:16:24 +0000329\end{verbatim}
330
Fred Drake20e01961998-02-19 15:09:35 +0000331but the version using \function{compile()} is more efficient when the
Guido van Rossum48d04371997-12-11 20:19:08 +0000332expression will be used several times in a single program.
Fred Drake20e01961998-02-19 15:09:35 +0000333%(The compiled version of the last pattern passed to
334%\function{regex.match()} or \function{regex.search()} is cached, so
335%programs that use only a single regular expression at a time needn't
336%worry about compiling regular expressions.)
Guido van Rossum1acceb01997-08-14 23:12:18 +0000337\end{funcdesc}
338
339\begin{funcdesc}{escape}{string}
Guido van Rossum48d04371997-12-11 20:19:08 +0000340 Return \var{string} with all non-alphanumerics backslashed; this is
341 useful if you want to match an arbitrary literal string that may have
342 regular expression metacharacters in it.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000343\end{funcdesc}
344
Fred Drake013ad981998-03-08 07:38:27 +0000345\begin{funcdesc}{match}{pattern, string\optional{, flags}}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000346 If zero or more characters at the beginning of \var{string} match
347 the regular expression \var{pattern}, return a corresponding
Fred Drake20e01961998-02-19 15:09:35 +0000348 \class{MatchObject} instance. Return \code{None} if the string does not
Guido van Rossum1acceb01997-08-14 23:12:18 +0000349 match the pattern; note that this is different from a zero-length
350 match.
351\end{funcdesc}
352
Fred Drake013ad981998-03-08 07:38:27 +0000353\begin{funcdesc}{search}{pattern, string\optional{, flags}}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000354 Scan through \var{string} looking for a location where the regular
Fred Drake023f87f1998-01-12 19:16:24 +0000355 expression \var{pattern} produces a match, and return a
Fred Drake20e01961998-02-19 15:09:35 +0000356 corresponding \class{MatchObject} instance.
Guido van Rossum0148bbf1997-12-22 22:41:40 +0000357 Return \code{None} if no
Guido van Rossum1acceb01997-08-14 23:12:18 +0000358 position in the string matches the pattern; note that this is
359 different from finding a zero-length match at some point in the string.
360\end{funcdesc}
361
Fred Drake013ad981998-03-08 07:38:27 +0000362\begin{funcdesc}{split}{pattern, string, \optional{, maxsplit\code{ = 0}}}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000363 Split \var{string} by the occurrences of \var{pattern}. If
364 capturing parentheses are used in pattern, then occurrences of
365 patterns or subpatterns are also returned.
Guido van Rossum97546391998-01-12 18:58:53 +0000366 If \var{maxsplit} is nonzero, at most \var{maxsplit} splits
367 occur, and the remainder of the string is returned as the final
368 element of the list. (Incompatibility note: in the original Python
369 1.5 release, \var{maxsplit} was ignored. This has been fixed in
370 later releases.)
Guido van Rossum1acceb01997-08-14 23:12:18 +0000371%
Fred Drake19479911998-02-13 06:58:54 +0000372\begin{verbatim}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000373>>> re.split('[\W]+', 'Words, words, words.')
374['Words', 'words', 'words', '']
375>>> re.split('([\W]+)', 'Words, words, words.')
376['Words', ', ', 'words', ', ', 'words', '.', '']
Guido van Rossum97546391998-01-12 18:58:53 +0000377>>> re.split('[\W]+', 'Words, words, words.', 1)
378['Words', 'words, words.']
Fred Drake19479911998-02-13 06:58:54 +0000379\end{verbatim}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000380%
381 This function combines and extends the functionality of
Fred Drake20e01961998-02-19 15:09:35 +0000382 the old \function{regsub.split()} and \function{regsub.splitx()}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000383\end{funcdesc}
384
Fred Drake013ad981998-03-08 07:38:27 +0000385\begin{funcdesc}{sub}{pattern, repl, string\optional{, count\code{ = 0}}}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000386Return the string obtained by replacing the leftmost non-overlapping
387occurrences of \var{pattern} in \var{string} by the replacement
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000388\var{repl}. If the pattern isn't found, \var{string} is returned
389unchanged. \var{repl} can be a string or a function; if a function,
390it is called for every non-overlapping occurance of \var{pattern}.
Guido van Rossum0b334101997-12-08 17:33:40 +0000391The function takes a single match object argument, and returns the
392replacement string. For example:
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000393%
Fred Drake19479911998-02-13 06:58:54 +0000394\begin{verbatim}
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000395>>> def dashrepl(matchobj):
396... if matchobj.group(0) == '-': return ' '
397... else: return '-'
398>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
399'pro--gram files'
Fred Drake19479911998-02-13 06:58:54 +0000400\end{verbatim}
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000401%
Guido van Rossum0b334101997-12-08 17:33:40 +0000402The pattern may be a string or a
Guido van Rossum48d04371997-12-11 20:19:08 +0000403regex object; if you need to specify
404regular expression flags, you must use a regex object, or use
405embedded modifiers in a pattern; e.g.
Fred Drake013ad981998-03-08 07:38:27 +0000406\samp{sub("(?i)b+", "x", "bbbb BBBB")} returns \code{'x x'}.
Fred Drake023f87f1998-01-12 19:16:24 +0000407
Guido van Rossum1acceb01997-08-14 23:12:18 +0000408The optional argument \var{count} is the maximum number of pattern
409occurrences to be replaced; count must be a non-negative integer, and
410the default value of 0 means to replace all occurrences.
411
412Empty matches for the pattern are replaced only when not adjacent to a
Fred Drake013ad981998-03-08 07:38:27 +0000413previous match, so \samp{sub('x*', '-', 'abc')} returns \code{'-a-b-c-'}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000414\end{funcdesc}
415
Fred Drake013ad981998-03-08 07:38:27 +0000416\begin{funcdesc}{subn}{pattern, repl, string\optional{, count\code{ = 0}}}
Fred Drake20e01961998-02-19 15:09:35 +0000417Perform the same operation as \function{sub()}, but return a tuple
Fred Drake023f87f1998-01-12 19:16:24 +0000418\code{(\var{new_string}, \var{number_of_subs_made})}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000419\end{funcdesc}
420
421\begin{excdesc}{error}
422 Exception raised when a string passed to one of the functions here
423 is not a valid regular expression (e.g., unmatched parentheses) or
Fred Drake013ad981998-03-08 07:38:27 +0000424 when some other error occurs during compilation or matching. It is
425 never an error if a string contains no match for a pattern.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000426\end{excdesc}
427
428\subsection{Regular Expression Objects}
429Compiled regular expression objects support the following methods and
430attributes:
431
Fred Drake19479911998-02-13 06:58:54 +0000432\setindexsubitem{(re method)}
Fred Drake013ad981998-03-08 07:38:27 +0000433\begin{funcdesc}{match}{string\optional{, pos}\optional{, endpos}}
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000434 If zero or more characters at the beginning of \var{string} match
435 this regular expression, return a corresponding
Fred Drake20e01961998-02-19 15:09:35 +0000436 \class{MatchObject} instance. Return \code{None} if the string does not
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000437 match the pattern; note that this is different from a zero-length
438 match.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000439
440 The optional second parameter \var{pos} gives an index in the string
Guido van Rossum48d04371997-12-11 20:19:08 +0000441 where the search is to start; it defaults to \code{0}. The
Fred Drake20e01961998-02-19 15:09:35 +0000442 \samp{\^} pattern character will match at the index where the
Guido van Rossum48d04371997-12-11 20:19:08 +0000443 search is to start.
Guido van Rossum0b334101997-12-08 17:33:40 +0000444
445 The optional parameter \var{endpos} limits how far the string will
446 be searched; it will be as if the string is \var{endpos} characters
447 long, so only the characters from \var{pos} to \var{endpos} will be
448 searched for a match.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000449\end{funcdesc}
450
Fred Drake013ad981998-03-08 07:38:27 +0000451\begin{funcdesc}{search}{string\optional{, pos}\optional{, endpos}}
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000452 Scan through \var{string} looking for a location where this regular
453 expression produces a match. Return \code{None} if no
454 position in the string matches the pattern; note that this is
455 different from finding a zero-length match at some point in the string.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000456
Guido van Rossum48d04371997-12-11 20:19:08 +0000457 The optional \var{pos} and \var{endpos} parameters have the same
Fred Drake20e01961998-02-19 15:09:35 +0000458 meaning as for the \method{match()} method.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000459\end{funcdesc}
460
Fred Drake013ad981998-03-08 07:38:27 +0000461\begin{funcdesc}{split}{string, \optional{, maxsplit\code{ = 0}}}
Fred Drake20e01961998-02-19 15:09:35 +0000462Identical to the \function{split()} function, using the compiled pattern.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000463\end{funcdesc}
464
Fred Drake013ad981998-03-08 07:38:27 +0000465\begin{funcdesc}{sub}{repl, string\optional{, count\code{ = 0}}}
Fred Drake20e01961998-02-19 15:09:35 +0000466Identical to the \function{sub()} function, using the compiled pattern.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000467\end{funcdesc}
468
Fred Drake013ad981998-03-08 07:38:27 +0000469\begin{funcdesc}{subn}{repl, string\optional{, count\code{ = 0}}}
Fred Drake20e01961998-02-19 15:09:35 +0000470Identical to the \function{subn()} function, using the compiled pattern.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000471\end{funcdesc}
472
Fred Drake19479911998-02-13 06:58:54 +0000473\setindexsubitem{(regex attribute)}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000474
475\begin{datadesc}{flags}
Fred Drake013ad981998-03-08 07:38:27 +0000476The flags argument used when the regex object was compiled, or
477\code{0} if no flags were provided.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000478\end{datadesc}
479
480\begin{datadesc}{groupindex}
Fred Drake013ad981998-03-08 07:38:27 +0000481A dictionary mapping any symbolic group names defined by
482\code{(?P<\var{id}>)} to group numbers. The dictionary is empty if no
Guido van Rossum1acceb01997-08-14 23:12:18 +0000483symbolic groups were used in the pattern.
484\end{datadesc}
485
486\begin{datadesc}{pattern}
487The pattern string from which the regex object was compiled.
488\end{datadesc}
489
Fred Drake023f87f1998-01-12 19:16:24 +0000490\subsection{Match Objects}
491
Fred Drake20e01961998-02-19 15:09:35 +0000492\class{MatchObject} instances support the following methods and attributes:
Guido van Rossum1acceb01997-08-14 23:12:18 +0000493
Guido van Rossum46503921998-01-19 23:14:17 +0000494\begin{funcdesc}{group}{\optional{group1, group2, ...}}
495Returns one or more subgroups of the match. If there is a single
496argument, the result is a single string; if there are
Guido van Rossum48d04371997-12-11 20:19:08 +0000497multiple arguments, the result is a tuple with one item per argument.
Guido van Rossum46503921998-01-19 23:14:17 +0000498Without arguments, \var{group1} defaults to zero (i.e. the whole match
499is returned).
500If a \var{groupN} argument is zero, the corresponding return value is the
Guido van Rossum48d04371997-12-11 20:19:08 +0000501entire matching string; if it is in the inclusive range [1..99], it is
502the string matching the the corresponding parenthesized group. If no
503such group exists, the corresponding result is
504\code{None}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000505
Guido van Rossum0b334101997-12-08 17:33:40 +0000506If the regular expression uses the \code{(?P<\var{name}>...)} syntax,
Guido van Rossum46503921998-01-19 23:14:17 +0000507the \var{groupN} arguments may also be strings identifying groups by
Guido van Rossum0b334101997-12-08 17:33:40 +0000508their group name.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000509
510A moderately complicated example:
Fred Drake023f87f1998-01-12 19:16:24 +0000511
512\begin{verbatim}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000513m = re.match(r"(?P<int>\d+)\.(\d*)", '3.14')
Fred Drake023f87f1998-01-12 19:16:24 +0000514\end{verbatim}
515
516After performing this match, \code{m.group(1)} is \code{'3'}, as is
Guido van Rossum46503921998-01-19 23:14:17 +0000517\code{m.group('int')}, and \code{m.group(2)} is \code{'14'}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000518\end{funcdesc}
519
Guido van Rossum48d04371997-12-11 20:19:08 +0000520\begin{funcdesc}{groups}{}
521Return a tuple containing all the subgroups of the match, from 1 up to
522however many groups are in the pattern. Groups that did not
Guido van Rossum97546391998-01-12 18:58:53 +0000523participate in the match have values of \code{None}. (Incompatibility
524note: in the original Python 1.5 release, if the tuple was one element
525long, a string would be returned instead. In later versions, a
526singleton tuple is returned in such cases.)
Guido van Rossum48d04371997-12-11 20:19:08 +0000527\end{funcdesc}
528
Guido van Rossum46503921998-01-19 23:14:17 +0000529\begin{funcdesc}{start}{\optional{group}}
Fred Drake013ad981998-03-08 07:38:27 +0000530\funcline{end}{\optional{group}}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000531Return the indices of the start and end of the substring
Guido van Rossum46503921998-01-19 23:14:17 +0000532matched by \var{group}; \var{group} defaults to zero (meaning the whole
533matched substring).
534Return \code{None} if \var{group} exists but
Guido van Rossume4eb2231997-12-17 00:23:39 +0000535did not contribute to the match. For a match object
Fred Drake023f87f1998-01-12 19:16:24 +0000536\var{m}, and a group \var{g} that did contribute to the match, the
537substring matched by group \var{g} (equivalent to
538\code{\var{m}.group(\var{g})}) is
539
540\begin{verbatim}
541m.string[m.start(g):m.end(g)]
542\end{verbatim}
543
Guido van Rossume4eb2231997-12-17 00:23:39 +0000544Note that
545\code{m.start(\var{group})} will equal \code{m.end(\var{group})} if
Fred Drake023f87f1998-01-12 19:16:24 +0000546\var{group} matched a null string. For example, after \code{\var{m} =
547re.search('b(c?)', 'cba')}, \code{\var{m}.start(0)} is 1,
548\code{\var{m}.end(0)} is 2, \code{\var{m}.start(1)} and
549\code{\var{m}.end(1)} are both 2, and \code{\var{m}.start(2)} raises
Fred Drake20e01961998-02-19 15:09:35 +0000550an \exception{IndexError} exception.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000551
552\end{funcdesc}
553
Guido van Rossum46503921998-01-19 23:14:17 +0000554\begin{funcdesc}{span}{\optional{group}}
Fred Drake20e01961998-02-19 15:09:35 +0000555For \class{MatchObject} \var{m}, return the 2-tuple
Fred Drake023f87f1998-01-12 19:16:24 +0000556\code{(\var{m}.start(\var{group}), \var{m}.end(\var{group}))}.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000557Note that if \var{group} did not contribute to the match, this is
Guido van Rossum46503921998-01-19 23:14:17 +0000558\code{(None, None)}. Again, \var{group} defaults to zero.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000559\end{funcdesc}
560
Guido van Rossum1acceb01997-08-14 23:12:18 +0000561\begin{datadesc}{pos}
Guido van Rossum0b334101997-12-08 17:33:40 +0000562The value of \var{pos} which was passed to the
Fred Drake20e01961998-02-19 15:09:35 +0000563\function{search()} or \function{match()} function. This is the index into
Fred Drake023f87f1998-01-12 19:16:24 +0000564the string at which the regex engine started looking for a match.
Guido van Rossum0b334101997-12-08 17:33:40 +0000565\end{datadesc}
566
567\begin{datadesc}{endpos}
568The value of \var{endpos} which was passed to the
Fred Drake20e01961998-02-19 15:09:35 +0000569\function{search()} or \function{match()} function. This is the index into
Fred Drake023f87f1998-01-12 19:16:24 +0000570the string beyond which the regex engine will not go.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000571\end{datadesc}
572
573\begin{datadesc}{re}
Fred Drake20e01961998-02-19 15:09:35 +0000574The regular expression object whose \method{match()} or
575\method{search()} method produced this \class{MatchObject} instance.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000576\end{datadesc}
577
578\begin{datadesc}{string}
Fred Drake20e01961998-02-19 15:09:35 +0000579The string passed to \function{match()} or \function{search()}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000580\end{datadesc}
581
Guido van Rossum1acceb01997-08-14 23:12:18 +0000582\begin{seealso}
Fred Drakef9951811997-12-29 16:37:04 +0000583\seetext{Jeffrey Friedl, \emph{Mastering Regular Expressions},
Fred Drake023f87f1998-01-12 19:16:24 +0000584O'Reilly. The Python material in this book dates from before the
Fred Drake20e01961998-02-19 15:09:35 +0000585\module{re} module, but it covers writing good regular expression
Fred Drake023f87f1998-01-12 19:16:24 +0000586patterns in great detail.}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000587\end{seealso}