blob: 3d0f3763a235aaf0a1fb3b000cc14e8bf626d400 [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\$]}
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
Fred Drake19479911998-02-13 06:58:54 +0000271\setindexsubitem{(in module re)}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000272
Fred Drake013ad981998-03-08 07:38:27 +0000273\begin{funcdesc}{compile}{pattern\optional{, flags}}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000274 Compile a regular expression pattern into a regular expression
Fred Drake20e01961998-02-19 15:09:35 +0000275 object, which can be used for matching using its \function{match()} and
276 \function{search()} methods, described below.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000277
Guido van Rossum0b334101997-12-08 17:33:40 +0000278 The expression's behaviour can be modified by specifying a
279 \var{flags} value. Values can be any of the following variables,
280 combined using bitwise OR (the \code{|} operator).
281
Fred Drake76547c51998-04-03 05:59:05 +0000282The sequence
283
284\begin{verbatim}
285prog = re.compile(pat)
286result = prog.match(str)
287\end{verbatim}
288
289is equivalent to
290
291\begin{verbatim}
292result = re.match(pat, str)
293\end{verbatim}
294
295but the version using \function{compile()} is more efficient when the
296expression will be used several times in a single program.
297%(The compiled version of the last pattern passed to
298%\function{regex.match()} or \function{regex.search()} is cached, so
299%programs that use only a single regular expression at a time needn't
300%worry about compiling regular expressions.)
301\end{funcdesc}
302
Fred Drake013ad981998-03-08 07:38:27 +0000303\begin{datadesc}{I}
304\dataline{IGNORECASE}
Fred Drake78f8e981997-12-29 21:39:39 +0000305Perform case-insensitive matching; expressions like \code{[A-Z]} will match
Guido van Rossum48d04371997-12-11 20:19:08 +0000306lowercase letters, too. This is not affected by the current locale.
Fred Drake013ad981998-03-08 07:38:27 +0000307\end{datadesc}
Guido van Rossum0b334101997-12-08 17:33:40 +0000308
Fred Drake013ad981998-03-08 07:38:27 +0000309\begin{datadesc}{L}
310\dataline{LOCALE}
Fred Drake78f8e981997-12-29 21:39:39 +0000311Make \code{\e w}, \code{\e W}, \code{\e b},
Guido van Rossum48d04371997-12-11 20:19:08 +0000312\code{\e B}, dependent on the current locale.
Fred Drake013ad981998-03-08 07:38:27 +0000313\end{datadesc}
Guido van Rossuma42c1781997-12-09 20:41:47 +0000314
Fred Drake013ad981998-03-08 07:38:27 +0000315\begin{datadesc}{M}
316\dataline{MULTILINE}
Fred Drake78f8e981997-12-29 21:39:39 +0000317When specified, the pattern character \code{\^} matches at the
Fred Drake023f87f1998-01-12 19:16:24 +0000318beginning of the string and at the beginning of each line
319(immediately following each newline); and the pattern character
Guido van Rossum48d04371997-12-11 20:19:08 +0000320\code{\$} matches at the end of the string and at the end of each line
321(immediately preceding each newline).
Guido van Rossum0b334101997-12-08 17:33:40 +0000322By default, \code{\^} matches only at the beginning of the string, and
323\code{\$} only at the end of the string and immediately before the
324newline (if any) at the end of the string.
Fred Drake013ad981998-03-08 07:38:27 +0000325\end{datadesc}
Guido van Rossum0b334101997-12-08 17:33:40 +0000326
Fred Drake013ad981998-03-08 07:38:27 +0000327\begin{datadesc}{S}
328\dataline{DOTALL}
Guido van Rossume9625e81998-04-02 01:32:24 +0000329Make the \code{.} special character match any character at all, including a
Guido van Rossum48d04371997-12-11 20:19:08 +0000330newline; without this flag, \code{.} will match anything \emph{except}
Fred Drake78f8e981997-12-29 21:39:39 +0000331a newline.
Fred Drake013ad981998-03-08 07:38:27 +0000332\end{datadesc}
Guido van Rossum48d04371997-12-11 20:19:08 +0000333
Fred Drake013ad981998-03-08 07:38:27 +0000334\begin{datadesc}{X}
335\dataline{VERBOSE}
Fred Drake78f8e981997-12-29 21:39:39 +0000336Ignore whitespace within the pattern
Guido van Rossum48d04371997-12-11 20:19:08 +0000337except when in a character class or preceded by an unescaped
338backslash, and, when a line contains a \code{\#} neither in a character
339class or preceded by an unescaped backslash, all characters from the
Fred Drake78f8e981997-12-29 21:39:39 +0000340leftmost such \code{\#} through the end of the line are ignored.
Fred Drake013ad981998-03-08 07:38:27 +0000341\end{datadesc}
Guido van Rossum0b334101997-12-08 17:33:40 +0000342
Guido van Rossum0b334101997-12-08 17:33:40 +0000343
Guido van Rossum1acceb01997-08-14 23:12:18 +0000344\begin{funcdesc}{escape}{string}
Guido van Rossum48d04371997-12-11 20:19:08 +0000345 Return \var{string} with all non-alphanumerics backslashed; this is
346 useful if you want to match an arbitrary literal string that may have
347 regular expression metacharacters in it.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000348\end{funcdesc}
349
Fred Drake013ad981998-03-08 07:38:27 +0000350\begin{funcdesc}{match}{pattern, string\optional{, flags}}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000351 If zero or more characters at the beginning of \var{string} match
352 the regular expression \var{pattern}, return a corresponding
Fred Drake20e01961998-02-19 15:09:35 +0000353 \class{MatchObject} instance. Return \code{None} if the string does not
Guido van Rossum1acceb01997-08-14 23:12:18 +0000354 match the pattern; note that this is different from a zero-length
355 match.
356\end{funcdesc}
357
Fred Drake013ad981998-03-08 07:38:27 +0000358\begin{funcdesc}{search}{pattern, string\optional{, flags}}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000359 Scan through \var{string} looking for a location where the regular
Fred Drake023f87f1998-01-12 19:16:24 +0000360 expression \var{pattern} produces a match, and return a
Fred Drake20e01961998-02-19 15:09:35 +0000361 corresponding \class{MatchObject} instance.
Guido van Rossum0148bbf1997-12-22 22:41:40 +0000362 Return \code{None} if no
Guido van Rossum1acceb01997-08-14 23:12:18 +0000363 position in the string matches the pattern; note that this is
364 different from finding a zero-length match at some point in the string.
365\end{funcdesc}
366
Fred Drake013ad981998-03-08 07:38:27 +0000367\begin{funcdesc}{split}{pattern, string, \optional{, maxsplit\code{ = 0}}}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000368 Split \var{string} by the occurrences of \var{pattern}. If
369 capturing parentheses are used in pattern, then occurrences of
370 patterns or subpatterns are also returned.
Guido van Rossum97546391998-01-12 18:58:53 +0000371 If \var{maxsplit} is nonzero, at most \var{maxsplit} splits
372 occur, and the remainder of the string is returned as the final
373 element of the list. (Incompatibility note: in the original Python
374 1.5 release, \var{maxsplit} was ignored. This has been fixed in
375 later releases.)
Guido van Rossum1acceb01997-08-14 23:12:18 +0000376%
Fred Drake19479911998-02-13 06:58:54 +0000377\begin{verbatim}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000378>>> re.split('[\W]+', 'Words, words, words.')
379['Words', 'words', 'words', '']
380>>> re.split('([\W]+)', 'Words, words, words.')
381['Words', ', ', 'words', ', ', 'words', '.', '']
Guido van Rossum97546391998-01-12 18:58:53 +0000382>>> re.split('[\W]+', 'Words, words, words.', 1)
383['Words', 'words, words.']
Fred Drake19479911998-02-13 06:58:54 +0000384\end{verbatim}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000385%
386 This function combines and extends the functionality of
Fred Drake20e01961998-02-19 15:09:35 +0000387 the old \function{regsub.split()} and \function{regsub.splitx()}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000388\end{funcdesc}
389
Fred Drake013ad981998-03-08 07:38:27 +0000390\begin{funcdesc}{sub}{pattern, repl, string\optional{, count\code{ = 0}}}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000391Return the string obtained by replacing the leftmost non-overlapping
392occurrences of \var{pattern} in \var{string} by the replacement
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000393\var{repl}. If the pattern isn't found, \var{string} is returned
394unchanged. \var{repl} can be a string or a function; if a function,
395it is called for every non-overlapping occurance of \var{pattern}.
Guido van Rossum0b334101997-12-08 17:33:40 +0000396The function takes a single match object argument, and returns the
397replacement string. For example:
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000398%
Fred Drake19479911998-02-13 06:58:54 +0000399\begin{verbatim}
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000400>>> def dashrepl(matchobj):
Guido van Rossume9625e81998-04-02 01:32:24 +0000401.... if matchobj.group(0) == '-': return ' '
402.... else: return '-'
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000403>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
404'pro--gram files'
Fred Drake19479911998-02-13 06:58:54 +0000405\end{verbatim}
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000406%
Guido van Rossum0b334101997-12-08 17:33:40 +0000407The pattern may be a string or a
Guido van Rossum48d04371997-12-11 20:19:08 +0000408regex object; if you need to specify
409regular expression flags, you must use a regex object, or use
410embedded modifiers in a pattern; e.g.
Fred Drake013ad981998-03-08 07:38:27 +0000411\samp{sub("(?i)b+", "x", "bbbb BBBB")} returns \code{'x x'}.
Fred Drake023f87f1998-01-12 19:16:24 +0000412
Guido van Rossum1acceb01997-08-14 23:12:18 +0000413The optional argument \var{count} is the maximum number of pattern
414occurrences to be replaced; count must be a non-negative integer, and
415the default value of 0 means to replace all occurrences.
416
417Empty matches for the pattern are replaced only when not adjacent to a
Fred Drake013ad981998-03-08 07:38:27 +0000418previous match, so \samp{sub('x*', '-', 'abc')} returns \code{'-a-b-c-'}.
Guido van Rossume9625e81998-04-02 01:32:24 +0000419
420If \var{repl} is a string, any backslash escapes in it are processed.
421That is, \samp{\e n} is converted to a single newline character,
422\samp{\e r} is converted to a linefeed, and so forth. Unknown escapes
423such as \samp{\e j} are XXX. Backreferences, such as \samp{\e 6} are
424replaced with the substring matched by group 6 in the pattern.
425
426In addition to character escapes and backreferences as described
427above, \samp{\e g<name>} will use the substring matched by the group
428named \samp{name}, as defined by the \samp{(?P<name>...)} syntax.
429\samp{\e g<number>} uses the corresponding group number; \samp{\e
430g<2>} is therefore equivalent to \samp{\e 2}, but isn't ambiguous in a
431replacement such as \samp{\e g<2>0}. \samp{\e 20} would be
432interpreted as a reference to group 20, not a reference to group 2
433followed by the literal character \samp{0}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000434\end{funcdesc}
435
Fred Drake013ad981998-03-08 07:38:27 +0000436\begin{funcdesc}{subn}{pattern, repl, string\optional{, count\code{ = 0}}}
Fred Drake20e01961998-02-19 15:09:35 +0000437Perform the same operation as \function{sub()}, but return a tuple
Fred Drake023f87f1998-01-12 19:16:24 +0000438\code{(\var{new_string}, \var{number_of_subs_made})}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000439\end{funcdesc}
440
441\begin{excdesc}{error}
442 Exception raised when a string passed to one of the functions here
443 is not a valid regular expression (e.g., unmatched parentheses) or
Fred Drake013ad981998-03-08 07:38:27 +0000444 when some other error occurs during compilation or matching. It is
445 never an error if a string contains no match for a pattern.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000446\end{excdesc}
447
448\subsection{Regular Expression Objects}
449Compiled regular expression objects support the following methods and
450attributes:
451
Fred Drake76547c51998-04-03 05:59:05 +0000452\begin{methoddesc}[RegexObject]{match}{string\optional{, pos}\optional{,
453 endpos}}
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000454 If zero or more characters at the beginning of \var{string} match
455 this regular expression, return a corresponding
Fred Drake20e01961998-02-19 15:09:35 +0000456 \class{MatchObject} instance. Return \code{None} if the string does not
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000457 match the pattern; note that this is different from a zero-length
458 match.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000459
460 The optional second parameter \var{pos} gives an index in the string
Guido van Rossum48d04371997-12-11 20:19:08 +0000461 where the search is to start; it defaults to \code{0}. The
Fred Drake20e01961998-02-19 15:09:35 +0000462 \samp{\^} pattern character will match at the index where the
Guido van Rossum48d04371997-12-11 20:19:08 +0000463 search is to start.
Guido van Rossum0b334101997-12-08 17:33:40 +0000464
465 The optional parameter \var{endpos} limits how far the string will
466 be searched; it will be as if the string is \var{endpos} characters
467 long, so only the characters from \var{pos} to \var{endpos} will be
468 searched for a match.
Fred Drake76547c51998-04-03 05:59:05 +0000469\end{methoddesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000470
Fred Drake76547c51998-04-03 05:59:05 +0000471\begin{methoddesc}[RegexObject]{search}{string\optional{, pos}\optional{,
472 endpos}}
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000473 Scan through \var{string} looking for a location where this regular
474 expression produces a match. Return \code{None} if no
475 position in the string matches the pattern; note that this is
476 different from finding a zero-length match at some point in the string.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000477
Guido van Rossum48d04371997-12-11 20:19:08 +0000478 The optional \var{pos} and \var{endpos} parameters have the same
Fred Drake20e01961998-02-19 15:09:35 +0000479 meaning as for the \method{match()} method.
Fred Drake76547c51998-04-03 05:59:05 +0000480\end{methoddesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000481
Fred Drake76547c51998-04-03 05:59:05 +0000482\begin{methoddesc}[RegexObject]{split}{string, \optional{,
483 maxsplit\code{ = 0}}}
Fred Drake20e01961998-02-19 15:09:35 +0000484Identical to the \function{split()} function, using the compiled pattern.
Fred Drake76547c51998-04-03 05:59:05 +0000485\end{methoddesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000486
Fred Drake76547c51998-04-03 05:59:05 +0000487\begin{methoddesc}[RegexObject]{sub}{repl, string\optional{, count\code{ = 0}}}
Fred Drake20e01961998-02-19 15:09:35 +0000488Identical to the \function{sub()} function, using the compiled pattern.
Fred Drake76547c51998-04-03 05:59:05 +0000489\end{methoddesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000490
Fred Drake76547c51998-04-03 05:59:05 +0000491\begin{methoddesc}[RegexObject]{subn}{repl, string\optional{,
492 count\code{ = 0}}}
Fred Drake20e01961998-02-19 15:09:35 +0000493Identical to the \function{subn()} function, using the compiled pattern.
Fred Drake76547c51998-04-03 05:59:05 +0000494\end{methoddesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000495
Guido van Rossum1acceb01997-08-14 23:12:18 +0000496
Fred Drake76547c51998-04-03 05:59:05 +0000497\begin{memberdesc}[RegexObject]{flags}
Fred Drake013ad981998-03-08 07:38:27 +0000498The flags argument used when the regex object was compiled, or
499\code{0} if no flags were provided.
Fred Drake76547c51998-04-03 05:59:05 +0000500\end{memberdesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000501
Fred Drake76547c51998-04-03 05:59:05 +0000502\begin{memberdesc}[RegexObject]{groupindex}
Fred Drake013ad981998-03-08 07:38:27 +0000503A dictionary mapping any symbolic group names defined by
504\code{(?P<\var{id}>)} to group numbers. The dictionary is empty if no
Guido van Rossum1acceb01997-08-14 23:12:18 +0000505symbolic groups were used in the pattern.
Fred Drake76547c51998-04-03 05:59:05 +0000506\end{memberdesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000507
Fred Drake76547c51998-04-03 05:59:05 +0000508\begin{memberdesc}[RegexObject]{pattern}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000509The pattern string from which the regex object was compiled.
Fred Drake76547c51998-04-03 05:59:05 +0000510\end{memberdesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000511
Fred Drake023f87f1998-01-12 19:16:24 +0000512\subsection{Match Objects}
513
Fred Drake20e01961998-02-19 15:09:35 +0000514\class{MatchObject} instances support the following methods and attributes:
Guido van Rossum1acceb01997-08-14 23:12:18 +0000515
Fred Drake76547c51998-04-03 05:59:05 +0000516\begin{methoddesc}[MatchObject]{group}{\optional{group1, group2, ...}}
Guido van Rossum46503921998-01-19 23:14:17 +0000517Returns one or more subgroups of the match. If there is a single
518argument, the result is a single string; if there are
Guido van Rossum48d04371997-12-11 20:19:08 +0000519multiple arguments, the result is a tuple with one item per argument.
Guido van Rossum46503921998-01-19 23:14:17 +0000520Without arguments, \var{group1} defaults to zero (i.e. the whole match
521is returned).
522If a \var{groupN} argument is zero, the corresponding return value is the
Guido van Rossum48d04371997-12-11 20:19:08 +0000523entire matching string; if it is in the inclusive range [1..99], it is
524the string matching the the corresponding parenthesized group. If no
525such group exists, the corresponding result is
526\code{None}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000527
Guido van Rossum0b334101997-12-08 17:33:40 +0000528If the regular expression uses the \code{(?P<\var{name}>...)} syntax,
Guido van Rossum46503921998-01-19 23:14:17 +0000529the \var{groupN} arguments may also be strings identifying groups by
Guido van Rossum0b334101997-12-08 17:33:40 +0000530their group name.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000531
532A moderately complicated example:
Fred Drake023f87f1998-01-12 19:16:24 +0000533
534\begin{verbatim}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000535m = re.match(r"(?P<int>\d+)\.(\d*)", '3.14')
Fred Drake023f87f1998-01-12 19:16:24 +0000536\end{verbatim}
537
538After performing this match, \code{m.group(1)} is \code{'3'}, as is
Guido van Rossum46503921998-01-19 23:14:17 +0000539\code{m.group('int')}, and \code{m.group(2)} is \code{'14'}.
Fred Drake76547c51998-04-03 05:59:05 +0000540\end{methoddesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000541
Fred Drake76547c51998-04-03 05:59:05 +0000542\begin{methoddesc}[MatchObject]{groups}{}
Guido van Rossum48d04371997-12-11 20:19:08 +0000543Return a tuple containing all the subgroups of the match, from 1 up to
544however many groups are in the pattern. Groups that did not
Guido van Rossum97546391998-01-12 18:58:53 +0000545participate in the match have values of \code{None}. (Incompatibility
546note: in the original Python 1.5 release, if the tuple was one element
547long, a string would be returned instead. In later versions, a
548singleton tuple is returned in such cases.)
Fred Drake76547c51998-04-03 05:59:05 +0000549\end{methoddesc}
Guido van Rossum48d04371997-12-11 20:19:08 +0000550
Fred Drake76547c51998-04-03 05:59:05 +0000551\begin{methoddesc}[MatchObject]{start}{\optional{group}}
Fred Drake013ad981998-03-08 07:38:27 +0000552\funcline{end}{\optional{group}}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000553Return the indices of the start and end of the substring
Guido van Rossum46503921998-01-19 23:14:17 +0000554matched by \var{group}; \var{group} defaults to zero (meaning the whole
555matched substring).
556Return \code{None} if \var{group} exists but
Guido van Rossume4eb2231997-12-17 00:23:39 +0000557did not contribute to the match. For a match object
Fred Drake023f87f1998-01-12 19:16:24 +0000558\var{m}, and a group \var{g} that did contribute to the match, the
559substring matched by group \var{g} (equivalent to
560\code{\var{m}.group(\var{g})}) is
561
562\begin{verbatim}
563m.string[m.start(g):m.end(g)]
564\end{verbatim}
565
Guido van Rossume4eb2231997-12-17 00:23:39 +0000566Note that
567\code{m.start(\var{group})} will equal \code{m.end(\var{group})} if
Fred Drake023f87f1998-01-12 19:16:24 +0000568\var{group} matched a null string. For example, after \code{\var{m} =
569re.search('b(c?)', 'cba')}, \code{\var{m}.start(0)} is 1,
570\code{\var{m}.end(0)} is 2, \code{\var{m}.start(1)} and
571\code{\var{m}.end(1)} are both 2, and \code{\var{m}.start(2)} raises
Fred Drake20e01961998-02-19 15:09:35 +0000572an \exception{IndexError} exception.
Fred Drake76547c51998-04-03 05:59:05 +0000573\end{methoddesc}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000574
Fred Drake76547c51998-04-03 05:59:05 +0000575\begin{methoddesc}[MatchObject]{span}{\optional{group}}
Fred Drake20e01961998-02-19 15:09:35 +0000576For \class{MatchObject} \var{m}, return the 2-tuple
Fred Drake023f87f1998-01-12 19:16:24 +0000577\code{(\var{m}.start(\var{group}), \var{m}.end(\var{group}))}.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000578Note that if \var{group} did not contribute to the match, this is
Guido van Rossum46503921998-01-19 23:14:17 +0000579\code{(None, None)}. Again, \var{group} defaults to zero.
Fred Drake76547c51998-04-03 05:59:05 +0000580\end{methoddesc}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000581
Fred Drake76547c51998-04-03 05:59:05 +0000582\begin{memberdesc}[MatchObject]{pos}
Guido van Rossum0b334101997-12-08 17:33:40 +0000583The value of \var{pos} which was passed to the
Fred Drake20e01961998-02-19 15:09:35 +0000584\function{search()} or \function{match()} function. This is the index into
Fred Drake023f87f1998-01-12 19:16:24 +0000585the string at which the regex engine started looking for a match.
Fred Drake76547c51998-04-03 05:59:05 +0000586\end{memberdesc}
Guido van Rossum0b334101997-12-08 17:33:40 +0000587
Fred Drake76547c51998-04-03 05:59:05 +0000588\begin{memberdesc}[MatchObject]{endpos}
Guido van Rossum0b334101997-12-08 17:33:40 +0000589The value of \var{endpos} which was passed to the
Fred Drake20e01961998-02-19 15:09:35 +0000590\function{search()} or \function{match()} function. This is the index into
Fred Drake023f87f1998-01-12 19:16:24 +0000591the string beyond which the regex engine will not go.
Fred Drake76547c51998-04-03 05:59:05 +0000592\end{memberdesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000593
Fred Drake76547c51998-04-03 05:59:05 +0000594\begin{memberdesc}[MatchObject]{re}
Fred Drake20e01961998-02-19 15:09:35 +0000595The regular expression object whose \method{match()} or
596\method{search()} method produced this \class{MatchObject} instance.
Fred Drake76547c51998-04-03 05:59:05 +0000597\end{memberdesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000598
Fred Drake76547c51998-04-03 05:59:05 +0000599\begin{memberdesc}[MatchObject]{string}
Fred Drake20e01961998-02-19 15:09:35 +0000600The string passed to \function{match()} or \function{search()}.
Fred Drake76547c51998-04-03 05:59:05 +0000601\end{memberdesc}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000602
Guido van Rossum1acceb01997-08-14 23:12:18 +0000603\begin{seealso}
Fred Drakef9951811997-12-29 16:37:04 +0000604\seetext{Jeffrey Friedl, \emph{Mastering Regular Expressions},
Fred Drake023f87f1998-01-12 19:16:24 +0000605O'Reilly. The Python material in this book dates from before the
Fred Drake20e01961998-02-19 15:09:35 +0000606\module{re} module, but it covers writing good regular expression
Fred Drake023f87f1998-01-12 19:16:24 +0000607patterns in great detail.}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000608\end{seealso}