blob: dbc94cc7fa26b7d54d6e356695b057a3371309ec [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.
Guido van Rossume9625e81998-04-02 01:32:24 +0000156Extensions usually do not create a new group;
157\code{(?P<\var{name}>...)} is the only exception to this rule.
Guido van Rossum0b334101997-12-08 17:33:40 +0000158Following are the currently supported extensions.
159%
Fred Drake20e01961998-02-19 15:09:35 +0000160\item[\code{(?iLmsx)}] (One or more letters from the set \samp{i},
161\samp{L}, \samp{m}, \samp{s}, \samp{x}.) The group matches
Fred Drake023f87f1998-01-12 19:16:24 +0000162the empty string; the letters set the corresponding flags
Fred Drake20e01961998-02-19 15:09:35 +0000163(\constant{re.I}, \constant{re.L}, \constant{re.M}, \constant{re.S},
164\constant{re.X}) for the entire regular expression. This is useful if
Guido van Rossume9625e81998-04-02 01:32:24 +0000165you wish to include the flags as part of the regular expression, instead
Fred Drake20e01961998-02-19 15:09:35 +0000166of passing a \var{flag} argument to the \function{compile()} function.
Guido van Rossum0b334101997-12-08 17:33:40 +0000167%
Guido van Rossum1acceb01997-08-14 23:12:18 +0000168\item[\code{(?:...)}] A non-grouping version of regular parentheses.
Guido van Rossume9625e81998-04-02 01:32:24 +0000169Matches whatever's inside the parentheses, but the substring matched by the
Guido van Rossum1acceb01997-08-14 23:12:18 +0000170group \emph{cannot} be retrieved after performing a match or
171referenced later in the pattern.
172%
173\item[\code{(?P<\var{name}>...)}] Similar to regular parentheses, but
Guido van Rossume9625e81998-04-02 01:32:24 +0000174the substring matched by the group is accessible via the symbolic group
Guido van Rossum1acceb01997-08-14 23:12:18 +0000175name \var{name}. Group names must be valid Python identifiers. A
176symbolic group is also a numbered group, just as if the group were not
177named. So the group named 'id' in the example above can also be
178referenced as the numbered group 1.
179
Guido van Rossum48d04371997-12-11 20:19:08 +0000180For example, if the pattern is
181\code{(?P<id>[a-zA-Z_]\e w*)}, the group can be referenced by its
Guido van Rossum1acceb01997-08-14 23:12:18 +0000182name in arguments to methods of match objects, such as \code{m.group('id')}
Fred Drake023f87f1998-01-12 19:16:24 +0000183or \code{m.end('id')}, and also by name in pattern text
184(e.g. \code{(?P=id)}) and replacement text (e.g. \code{\e g<id>}).
Guido van Rossum1acceb01997-08-14 23:12:18 +0000185%
Fred Drake023f87f1998-01-12 19:16:24 +0000186\item[\code{(?P=\var{name})}] Matches whatever text was matched by the
187earlier group named \var{name}.
Guido van Rossum48d04371997-12-11 20:19:08 +0000188%
Fred Drake023f87f1998-01-12 19:16:24 +0000189\item[\code{(?\#...)}] A comment; the contents of the parentheses are
190simply ignored.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000191%
Fred Drake023f87f1998-01-12 19:16:24 +0000192\item[\code{(?=...)}] Matches if \code{...} matches next, but doesn't
193consume any of the string. This is called a lookahead assertion. For
194example, \code{Isaac (?=Asimov)} will match 'Isaac~' only if it's
195followed by 'Asimov'.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000196%
Fred Drake023f87f1998-01-12 19:16:24 +0000197\item[\code{(?!...)}] Matches if \code{...} doesn't match next. This
198is a negative lookahead assertion. For example,
199\code{Isaac (?!Asimov)} will match 'Isaac~' only if it's \emph{not}
200followed by 'Asimov'.
Guido van Rossum0b334101997-12-08 17:33:40 +0000201
Fred Drake2705e801998-02-16 21:21:13 +0000202\end{list}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000203
Fred Drake20e01961998-02-19 15:09:35 +0000204The special sequences consist of \samp{\e} and a character from the
Guido van Rossum1acceb01997-08-14 23:12:18 +0000205list below. If the ordinary character is not on the list, then the
206resulting RE will match the second character. For example,
Fred Drake20e01961998-02-19 15:09:35 +0000207\code{\e\$} matches the character \samp{\$}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000208
Fred Drake2705e801998-02-16 21:21:13 +0000209\begin{list}{}{\leftmargin \MyLeftMargin \labelwidth \MyLabelWidth}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000210
211%
212\item[\code{\e \var{number}}] Matches the contents of the group of the
Guido van Rossum0b334101997-12-08 17:33:40 +0000213same number. Groups are numbered starting from 1. For example,
214\code{(.+) \e 1} matches 'the the' or '55 55', but not 'the end' (note
215the space after the group). This special sequence can only be used to
216match one of the first 99 groups. If the first digit of \var{number}
217is 0, or \var{number} is 3 octal digits long, it will not be interpreted
218as a group match, but as the character with octal value \var{number}.
Guido van Rossume9625e81998-04-02 01:32:24 +0000219Inside the \code{[} and \code{]} of a character class, all numeric
220escapes are treated as characters.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000221%
222\item[\code{\e A}] Matches only at the start of the string.
223%
224\item[\code{\e b}] Matches the empty string, but only at the
225beginning or end of a word. A word is defined as a sequence of
226alphanumeric characters, so the end of a word is indicated by
Guido van Rossum48d04371997-12-11 20:19:08 +0000227whitespace or a non-alphanumeric character. Inside a character range,
228\code{\e b} represents the backspace character, for compatibility with
229Python's string literals.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000230%
Guido van Rossum0b334101997-12-08 17:33:40 +0000231\item[\code{\e B}] Matches the empty string, but only when it is
232\emph{not} at the beginning or end of a word.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000233%
234\item[\code{\e d}]Matches any decimal digit; this is
235equivalent to the set \code{[0-9]}.
236%
237\item[\code{\e D}]Matches any non-digit character; this is
Fred Drake20e01961998-02-19 15:09:35 +0000238equivalent to the set \code{[\^0-9]}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000239%
240\item[\code{\e s}]Matches any whitespace character; this is
241equivalent to the set \code{[ \e t\e n\e r\e f\e v]}.
242%
243\item[\code{\e S}]Matches any non-whitespace character; this is
Guido van Rossumf5370f41998-02-11 22:52:47 +0000244equivalent to the set \code{[\^\ \e t\e n\e r\e f\e v]}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000245%
Fred Drake20e01961998-02-19 15:09:35 +0000246\item[\code{\e w}]When the \constant{LOCALE} flag is not specified,
Fred Drake023f87f1998-01-12 19:16:24 +0000247matches any alphanumeric character; this is equivalent to the set
Fred Drake20e01961998-02-19 15:09:35 +0000248\code{[a-zA-Z0-9_]}. With \constant{LOCALE}, it will match the set
Fred Drake023f87f1998-01-12 19:16:24 +0000249\code{[0-9_]} plus whatever characters are defined as letters for the
250current locale.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000251%
Fred Drake20e01961998-02-19 15:09:35 +0000252\item[\code{\e W}]When the \constant{LOCALE} flag is not specified,
Fred Drake023f87f1998-01-12 19:16:24 +0000253matches any non-alphanumeric character; this is equivalent to the set
Fred Drake20e01961998-02-19 15:09:35 +0000254\code{[\^a-zA-Z0-9_]}. With \constant{LOCALE}, it will match any
Fred Drake023f87f1998-01-12 19:16:24 +0000255character not in the set \code{[0-9_]}, and not defined as a letter
Guido van Rossum0b334101997-12-08 17:33:40 +0000256for the current locale.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000257
258\item[\code{\e Z}]Matches only at the end of the string.
259%
260
261\item[\code{\e \e}] Matches a literal backslash.
262
Fred Drake2705e801998-02-16 21:21:13 +0000263\end{list}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000264
265\subsection{Module Contents}
Fred Drake78f8e981997-12-29 21:39:39 +0000266\nodename{Contents of Module re}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000267
268The module defines the following functions and constants, and an exception:
269
Fred Drake19479911998-02-13 06:58:54 +0000270\setindexsubitem{(in module re)}
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 Drake013ad981998-03-08 07:38:27 +0000281\begin{datadesc}{I}
282\dataline{IGNORECASE}
Fred Drake78f8e981997-12-29 21:39:39 +0000283Perform case-insensitive matching; expressions like \code{[A-Z]} will match
Guido van Rossum48d04371997-12-11 20:19:08 +0000284lowercase letters, too. This is not affected by the current locale.
Fred Drake013ad981998-03-08 07:38:27 +0000285\end{datadesc}
Guido van Rossum0b334101997-12-08 17:33:40 +0000286
Fred Drake013ad981998-03-08 07:38:27 +0000287\begin{datadesc}{L}
288\dataline{LOCALE}
Fred Drake78f8e981997-12-29 21:39:39 +0000289Make \code{\e w}, \code{\e W}, \code{\e b},
Guido van Rossum48d04371997-12-11 20:19:08 +0000290\code{\e B}, dependent on the current locale.
Fred Drake013ad981998-03-08 07:38:27 +0000291\end{datadesc}
Guido van Rossuma42c1781997-12-09 20:41:47 +0000292
Fred Drake013ad981998-03-08 07:38:27 +0000293\begin{datadesc}{M}
294\dataline{MULTILINE}
Fred Drake78f8e981997-12-29 21:39:39 +0000295When specified, the pattern character \code{\^} matches at the
Fred Drake023f87f1998-01-12 19:16:24 +0000296beginning of the string and at the beginning of each line
297(immediately following each newline); and the pattern character
Guido van Rossum48d04371997-12-11 20:19:08 +0000298\code{\$} matches at the end of the string and at the end of each line
299(immediately preceding each newline).
Guido van Rossum0b334101997-12-08 17:33:40 +0000300By default, \code{\^} matches only at the beginning of the string, and
301\code{\$} only at the end of the string and immediately before the
302newline (if any) at the end of the string.
Fred Drake013ad981998-03-08 07:38:27 +0000303\end{datadesc}
Guido van Rossum0b334101997-12-08 17:33:40 +0000304
Fred Drake013ad981998-03-08 07:38:27 +0000305\begin{datadesc}{S}
306\dataline{DOTALL}
Guido van Rossume9625e81998-04-02 01:32:24 +0000307Make the \code{.} special character match any character at all, including a
Guido van Rossum48d04371997-12-11 20:19:08 +0000308newline; without this flag, \code{.} will match anything \emph{except}
Fred Drake78f8e981997-12-29 21:39:39 +0000309a newline.
Fred Drake013ad981998-03-08 07:38:27 +0000310\end{datadesc}
Guido van Rossum48d04371997-12-11 20:19:08 +0000311
Fred Drake013ad981998-03-08 07:38:27 +0000312\begin{datadesc}{X}
313\dataline{VERBOSE}
Fred Drake78f8e981997-12-29 21:39:39 +0000314Ignore whitespace within the pattern
Guido van Rossum48d04371997-12-11 20:19:08 +0000315except when in a character class or preceded by an unescaped
316backslash, and, when a line contains a \code{\#} neither in a character
317class or preceded by an unescaped backslash, all characters from the
Fred Drake78f8e981997-12-29 21:39:39 +0000318leftmost such \code{\#} through the end of the line are ignored.
Fred Drake013ad981998-03-08 07:38:27 +0000319\end{datadesc}
Guido van Rossum0b334101997-12-08 17:33:40 +0000320
Guido van Rossum0b334101997-12-08 17:33:40 +0000321
Fred Drake78f8e981997-12-29 21:39:39 +0000322The sequence
Fred Drake013ad981998-03-08 07:38:27 +0000323
Fred Drake19479911998-02-13 06:58:54 +0000324\begin{verbatim}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000325prog = re.compile(pat)
326result = prog.match(str)
Fred Drake19479911998-02-13 06:58:54 +0000327\end{verbatim}
Fred Drake013ad981998-03-08 07:38:27 +0000328
Guido van Rossum1acceb01997-08-14 23:12:18 +0000329is equivalent to
Fred Drake023f87f1998-01-12 19:16:24 +0000330
331\begin{verbatim}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000332result = re.match(pat, str)
Fred Drake023f87f1998-01-12 19:16:24 +0000333\end{verbatim}
334
Fred Drake20e01961998-02-19 15:09:35 +0000335but the version using \function{compile()} is more efficient when the
Guido van Rossum48d04371997-12-11 20:19:08 +0000336expression will be used several times in a single program.
Fred Drake20e01961998-02-19 15:09:35 +0000337%(The compiled version of the last pattern passed to
338%\function{regex.match()} or \function{regex.search()} is cached, so
339%programs that use only a single regular expression at a time needn't
340%worry about compiling regular expressions.)
Guido van Rossum1acceb01997-08-14 23:12:18 +0000341\end{funcdesc}
342
343\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
422such as \samp{\e j} are XXX. Backreferences, such as \samp{\e 6} are
423replaced 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 Drake19479911998-02-13 06:58:54 +0000451\setindexsubitem{(re method)}
Fred Drake013ad981998-03-08 07:38:27 +0000452\begin{funcdesc}{match}{string\optional{, pos}\optional{, 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.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000468\end{funcdesc}
469
Fred Drake013ad981998-03-08 07:38:27 +0000470\begin{funcdesc}{search}{string\optional{, pos}\optional{, endpos}}
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000471 Scan through \var{string} looking for a location where this regular
472 expression produces a match. Return \code{None} if no
473 position in the string matches the pattern; note that this is
474 different from finding a zero-length match at some point in the string.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000475
Guido van Rossum48d04371997-12-11 20:19:08 +0000476 The optional \var{pos} and \var{endpos} parameters have the same
Fred Drake20e01961998-02-19 15:09:35 +0000477 meaning as for the \method{match()} method.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000478\end{funcdesc}
479
Fred Drake013ad981998-03-08 07:38:27 +0000480\begin{funcdesc}{split}{string, \optional{, maxsplit\code{ = 0}}}
Fred Drake20e01961998-02-19 15:09:35 +0000481Identical to the \function{split()} function, using the compiled pattern.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000482\end{funcdesc}
483
Fred Drake013ad981998-03-08 07:38:27 +0000484\begin{funcdesc}{sub}{repl, string\optional{, count\code{ = 0}}}
Fred Drake20e01961998-02-19 15:09:35 +0000485Identical to the \function{sub()} function, using the compiled pattern.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000486\end{funcdesc}
487
Fred Drake013ad981998-03-08 07:38:27 +0000488\begin{funcdesc}{subn}{repl, string\optional{, count\code{ = 0}}}
Fred Drake20e01961998-02-19 15:09:35 +0000489Identical to the \function{subn()} function, using the compiled pattern.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000490\end{funcdesc}
491
Fred Drake19479911998-02-13 06:58:54 +0000492\setindexsubitem{(regex attribute)}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000493
494\begin{datadesc}{flags}
Fred Drake013ad981998-03-08 07:38:27 +0000495The flags argument used when the regex object was compiled, or
496\code{0} if no flags were provided.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000497\end{datadesc}
498
499\begin{datadesc}{groupindex}
Fred Drake013ad981998-03-08 07:38:27 +0000500A dictionary mapping any symbolic group names defined by
501\code{(?P<\var{id}>)} to group numbers. The dictionary is empty if no
Guido van Rossum1acceb01997-08-14 23:12:18 +0000502symbolic groups were used in the pattern.
503\end{datadesc}
504
505\begin{datadesc}{pattern}
506The pattern string from which the regex object was compiled.
507\end{datadesc}
508
Fred Drake023f87f1998-01-12 19:16:24 +0000509\subsection{Match Objects}
510
Fred Drake20e01961998-02-19 15:09:35 +0000511\class{MatchObject} instances support the following methods and attributes:
Guido van Rossum1acceb01997-08-14 23:12:18 +0000512
Guido van Rossum46503921998-01-19 23:14:17 +0000513\begin{funcdesc}{group}{\optional{group1, group2, ...}}
514Returns one or more subgroups of the match. If there is a single
515argument, the result is a single string; if there are
Guido van Rossum48d04371997-12-11 20:19:08 +0000516multiple arguments, the result is a tuple with one item per argument.
Guido van Rossum46503921998-01-19 23:14:17 +0000517Without arguments, \var{group1} defaults to zero (i.e. the whole match
518is returned).
519If a \var{groupN} argument is zero, the corresponding return value is the
Guido van Rossum48d04371997-12-11 20:19:08 +0000520entire matching string; if it is in the inclusive range [1..99], it is
521the string matching the the corresponding parenthesized group. If no
522such group exists, the corresponding result is
523\code{None}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000524
Guido van Rossum0b334101997-12-08 17:33:40 +0000525If the regular expression uses the \code{(?P<\var{name}>...)} syntax,
Guido van Rossum46503921998-01-19 23:14:17 +0000526the \var{groupN} arguments may also be strings identifying groups by
Guido van Rossum0b334101997-12-08 17:33:40 +0000527their group name.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000528
529A moderately complicated example:
Fred Drake023f87f1998-01-12 19:16:24 +0000530
531\begin{verbatim}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000532m = re.match(r"(?P<int>\d+)\.(\d*)", '3.14')
Fred Drake023f87f1998-01-12 19:16:24 +0000533\end{verbatim}
534
535After performing this match, \code{m.group(1)} is \code{'3'}, as is
Guido van Rossum46503921998-01-19 23:14:17 +0000536\code{m.group('int')}, and \code{m.group(2)} is \code{'14'}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000537\end{funcdesc}
538
Guido van Rossum48d04371997-12-11 20:19:08 +0000539\begin{funcdesc}{groups}{}
540Return a tuple containing all the subgroups of the match, from 1 up to
541however many groups are in the pattern. Groups that did not
Guido van Rossum97546391998-01-12 18:58:53 +0000542participate in the match have values of \code{None}. (Incompatibility
543note: in the original Python 1.5 release, if the tuple was one element
544long, a string would be returned instead. In later versions, a
545singleton tuple is returned in such cases.)
Guido van Rossum48d04371997-12-11 20:19:08 +0000546\end{funcdesc}
547
Guido van Rossum46503921998-01-19 23:14:17 +0000548\begin{funcdesc}{start}{\optional{group}}
Fred Drake013ad981998-03-08 07:38:27 +0000549\funcline{end}{\optional{group}}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000550Return the indices of the start and end of the substring
Guido van Rossum46503921998-01-19 23:14:17 +0000551matched by \var{group}; \var{group} defaults to zero (meaning the whole
552matched substring).
553Return \code{None} if \var{group} exists but
Guido van Rossume4eb2231997-12-17 00:23:39 +0000554did not contribute to the match. For a match object
Fred Drake023f87f1998-01-12 19:16:24 +0000555\var{m}, and a group \var{g} that did contribute to the match, the
556substring matched by group \var{g} (equivalent to
557\code{\var{m}.group(\var{g})}) is
558
559\begin{verbatim}
560m.string[m.start(g):m.end(g)]
561\end{verbatim}
562
Guido van Rossume4eb2231997-12-17 00:23:39 +0000563Note that
564\code{m.start(\var{group})} will equal \code{m.end(\var{group})} if
Fred Drake023f87f1998-01-12 19:16:24 +0000565\var{group} matched a null string. For example, after \code{\var{m} =
566re.search('b(c?)', 'cba')}, \code{\var{m}.start(0)} is 1,
567\code{\var{m}.end(0)} is 2, \code{\var{m}.start(1)} and
568\code{\var{m}.end(1)} are both 2, and \code{\var{m}.start(2)} raises
Fred Drake20e01961998-02-19 15:09:35 +0000569an \exception{IndexError} exception.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000570
571\end{funcdesc}
572
Guido van Rossum46503921998-01-19 23:14:17 +0000573\begin{funcdesc}{span}{\optional{group}}
Fred Drake20e01961998-02-19 15:09:35 +0000574For \class{MatchObject} \var{m}, return the 2-tuple
Fred Drake023f87f1998-01-12 19:16:24 +0000575\code{(\var{m}.start(\var{group}), \var{m}.end(\var{group}))}.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000576Note that if \var{group} did not contribute to the match, this is
Guido van Rossum46503921998-01-19 23:14:17 +0000577\code{(None, None)}. Again, \var{group} defaults to zero.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000578\end{funcdesc}
579
Guido van Rossum1acceb01997-08-14 23:12:18 +0000580\begin{datadesc}{pos}
Guido van Rossum0b334101997-12-08 17:33:40 +0000581The value of \var{pos} which was passed to the
Fred Drake20e01961998-02-19 15:09:35 +0000582\function{search()} or \function{match()} function. This is the index into
Fred Drake023f87f1998-01-12 19:16:24 +0000583the string at which the regex engine started looking for a match.
Guido van Rossum0b334101997-12-08 17:33:40 +0000584\end{datadesc}
585
586\begin{datadesc}{endpos}
587The value of \var{endpos} 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 beyond which the regex engine will not go.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000590\end{datadesc}
591
592\begin{datadesc}{re}
Fred Drake20e01961998-02-19 15:09:35 +0000593The regular expression object whose \method{match()} or
594\method{search()} method produced this \class{MatchObject} instance.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000595\end{datadesc}
596
597\begin{datadesc}{string}
Fred Drake20e01961998-02-19 15:09:35 +0000598The string passed to \function{match()} or \function{search()}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000599\end{datadesc}
600
Guido van Rossum1acceb01997-08-14 23:12:18 +0000601\begin{seealso}
Fred Drakef9951811997-12-29 16:37:04 +0000602\seetext{Jeffrey Friedl, \emph{Mastering Regular Expressions},
Fred Drake023f87f1998-01-12 19:16:24 +0000603O'Reilly. The Python material in this book dates from before the
Fred Drake20e01961998-02-19 15:09:35 +0000604\module{re} module, but it covers writing good regular expression
Fred Drake023f87f1998-01-12 19:16:24 +0000605patterns in great detail.}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000606\end{seealso}