blob: 65c47ff0bd8c65c8f0367e3c2339e83331a77867 [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
6% XXX Remove before 1.5final release.
Fred Drake78f8e981997-12-29 21:39:39 +00007%{\large\bf This documentation is preliminary and incomplete. If you
8%find a bug or documentation error, or just find something unclear,
9%please send a message to
10%\code{string-sig@python.org}, and we'll fix it.}
Guido van Rossum1acceb01997-08-14 23:12:18 +000011
12This module provides regular expression matching operations similar to
Guido van Rossum0b334101997-12-08 17:33:40 +000013those found in Perl. It's 8-bit clean: both patterns and strings may
14contain null bytes and characters whose high bit is set. It is always
15available.
Guido van Rossum1acceb01997-08-14 23:12:18 +000016
17Regular expressions use the backslash character (\code{\e}) to
18indicate special forms or to allow special characters to be used
19without invoking their special meaning. This collides with Python's
20usage of the same character for the same purpose in string literals;
21for example, to match a literal backslash, one might have to write
Guido van Rossum0b334101997-12-08 17:33:40 +000022\code{\e\e\e\e} as the pattern string, because the regular expression
23must be \code{\e\e}, and each backslash must be expressed as
24\code{\e\e} inside a regular Python string literal.
Guido van Rossum1acceb01997-08-14 23:12:18 +000025
26The solution is to use Python's raw string notation for regular
27expression patterns; backslashes are not handled in any special way in
28a string literal prefixed with 'r'. So \code{r"\e n"} is a two
29character string containing a backslash and the letter 'n', while
30\code{"\e n"} is a one-character string containing a newline. Usually
31patterns will be expressed in Python code using this raw string notation.
32
33% XXX Can the following section be dropped, or should it be boiled down?
34
35%\strong{Please note:} There is a little-known fact about Python string
36%literals which means that you don't usually have to worry about
37%doubling backslashes, even though they are used to escape special
38%characters in string literals as well as in regular expressions. This
39%is because Python doesn't remove backslashes from string literals if
40%they are followed by an unrecognized escape character.
41%\emph{However}, if you want to include a literal \dfn{backslash} in a
42%regular expression represented as a string literal, you have to
43%\emph{quadruple} it or enclose it in a singleton character class.
44%E.g.\ to extract \LaTeX\ \code{\e section\{{\rm
45%\ldots}\}} headers from a document, you can use this pattern:
46%\code{'[\e ] section\{\e (.*\e )\}'}. \emph{Another exception:}
47%the escape sequence \code{\e b} is significant in string literals
48%(where it means the ASCII bell character) as well as in Emacs regular
49%expressions (where it stands for a word boundary), so in order to
50%search for a word boundary, you should use the pattern \code{'\e \e b'}.
51%Similarly, a backslash followed by a digit 0-7 should be doubled to
52%avoid interpretation as an octal escape.
53
Guido van Rossum48d04371997-12-11 20:19:08 +000054\subsection{Regular Expression Syntax}
Guido van Rossum1acceb01997-08-14 23:12:18 +000055
56A regular expression (or RE) specifies a set of strings that matches
57it; the functions in this module let you check if a particular string
58matches a given regular expression (or if a given regular expression
59matches a particular string, which comes down to the same thing).
60
61Regular expressions can be concatenated to form new regular
62expressions; if \emph{A} and \emph{B} are both regular expressions,
63then \emph{AB} is also an regular expression. If a string \emph{p}
64matches A and another string \emph{q} matches B, the string \emph{pq}
65will match AB. Thus, complex expressions can easily be constructed
66from simpler primitive expressions like the ones described here. For
67details of the theory and implementation of regular expressions,
68consult the Friedl book referenced below, or almost any textbook about
69compiler construction.
70
Guido van Rossum0b334101997-12-08 17:33:40 +000071A brief explanation of the format of regular expressions follows.
72%For further information and a gentler presentation, consult XXX somewhere.
Guido van Rossum1acceb01997-08-14 23:12:18 +000073
74Regular expressions can contain both special and ordinary characters.
75Most ordinary characters, like '\code{A}', '\code{a}', or '\code{0}',
76are the simplest regular expressions; they simply match themselves.
77You can concatenate ordinary characters, so '\code{last}' matches the
78characters 'last'. (In the rest of this section, we'll write RE's in
79\code{this special font}, usually without quotes, and strings to be
80matched 'in single quotes'.)
81
82Some characters, like \code{|} or \code{(}, are special. Special
83characters either stand for classes of ordinary characters, or affect
84how the regular expressions around them are interpreted.
85
86The special characters are:
87\begin{itemize}
88\item[\code{.}] (Dot.) In the default mode, this matches any
89character except a newline. If the \code{DOTALL} flag has been
90specified, this matches any character including a newline.
91\item[\code{\^}] (Caret.) Matches the start of the string, and in
92\code{MULTILINE} mode also immediately after each newline.
Guido van Rossum48d04371997-12-11 20:19:08 +000093\item[\code{\$}] Matches the end of the string, and in
94\code{MULTILINE} mode also matches before a newline.
Guido van Rossum1acceb01997-08-14 23:12:18 +000095\code{foo} matches both 'foo' and 'foobar', while the regular
Guido van Rossum48d04371997-12-11 20:19:08 +000096expression \code{foo\$} matches only 'foo'.
Guido van Rossum1acceb01997-08-14 23:12:18 +000097%
98\item[\code{*}] Causes the resulting RE to
99match 0 or more repetitions of the preceding RE, as many repetitions
100as are possible. \code{ab*} will
101match 'a', 'ab', or 'a' followed by any number of 'b's.
102%
103\item[\code{+}] Causes the
104resulting RE to match 1 or more repetitions of the preceding RE.
105\code{ab+} will match 'a' followed by any non-zero number of 'b's; it
106will not match just 'a'.
107%
108\item[\code{?}] Causes the resulting RE to
109match 0 or 1 repetitions of the preceding RE. \code{ab?} will
110match either 'a' or 'ab'.
111\item[\code{*?}, \code{+?}, \code{??}] The \code{*}, \code{+}, and
112\code{?} qualifiers are all \dfn{greedy}; they match as much text as
113possible. Sometimes this behaviour isn't desired; if the RE
114\code{<.*>} is matched against \code{<H1>title</H1>}, it will match the
115entire string, and not just \code{<H1>}.
116Adding \code{?} after the qualifier makes it perform the match in
117\dfn{non-greedy} or \dfn{minimal} fashion; as few characters as
118possible will be matched. Using \code{.*?} in the previous
Guido van Rossum0b334101997-12-08 17:33:40 +0000119expression will match only \code{<H1>}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000120%
Guido van Rossum0148bbf1997-12-22 22:41:40 +0000121\item[\code{\{\var{m},\var{n}\}}] Causes the resulting RE to match from
122\var{m} to \var{n} repetitions of the preceding RE, attempting to
123match as many repetitions as possible. For example, \code{a\{3,5\}}
124will match from 3 to 5 'a' characters.
125%
126\item[\code{\{\var{m},\var{n}\}?}] Causes the resulting RE to
127match from \var{m} to \var{n} repetitions of the preceding RE,
128attempting to match as \emph{few} repetitions as possible. This is
129the non-greedy version of the previous qualifier. For example, on the
1306-character string 'aaaaaa', \code{a\{3,5\}} will match 5 'a'
131characters, while \code{a\{3,5\}?} will only match 3 characters.
132%
Guido van Rossum1acceb01997-08-14 23:12:18 +0000133\item[\code{\e}] Either escapes special characters (permitting you to match
134characters like '*?+\&\$'), or signals a special sequence; special
135sequences are discussed below.
136
137If you're not using a raw string to
138express the pattern, remember that Python also uses the
139backslash as an escape sequence in string literals; if the escape
140sequence isn't recognized by Python's parser, the backslash and
141subsequent character are included in the resulting string. However,
142if Python would recognize the resulting sequence, the backslash should
143be repeated twice. This is complicated and hard to understand, so
Guido van Rossum48d04371997-12-11 20:19:08 +0000144it's highly recommended that you use raw strings for all but the simplest expressions.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000145%
146\item[\code{[]}] Used to indicate a set of characters. Characters can
Guido van Rossum48d04371997-12-11 20:19:08 +0000147be listed individually, or a range of characters can be indicated by
148giving two characters and separating them by a '-'. Special
149characters are not active inside sets. For example, \code{[akm\$]}
150will match any of the characters 'a', 'k', 'm', or '\$'; \code{[a-z]}
151will match any lowercase letter and \code{[a-zA-Z0-9]} matches any
152letter or digit. Character classes such as \code{\e w} or \code {\e
153S} (defined below) are also acceptable inside a range. If you want to
154include a \code{]} or a \code{-} inside a set, precede it with a
155backslash.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000156
157Characters \emph{not} within a range can be matched by including a
158\code{\^} as the first character of the set; \code{\^} elsewhere will
159simply match the '\code{\^}' character.
160%
161\item[\code{|}]\code{A|B}, where A and B can be arbitrary REs,
162creates a regular expression that will match either A or B. This can
163be used inside groups (see below) as well. To match a literal '|',
164use \code{\e|}, or enclose it inside a character class, like \code{[|]}.
165%
Guido van Rossum48d04371997-12-11 20:19:08 +0000166\item[\code{(...)}] Matches whatever regular expression is inside the
167parentheses, and indicates the start and end of a group; the contents
168of a group can be retrieved after a match has been performed, and can
169be matched later in the string with the \code{\e \var{number}} special
170sequence, described below. To match the literals '(' or ')',
Guido van Rossum1acceb01997-08-14 23:12:18 +0000171use \code{\e(} or \code{\e)}, or enclose them inside a character
172class: \code{[(] [)]}.
173%
Guido van Rossum0b334101997-12-08 17:33:40 +0000174\item[\code{(?...)}] This is an extension notation (a '?' following a
175'(' is not meaningful otherwise). The first character after the '?'
176determines what the meaning and further syntax of the construct is.
177Following are the currently supported extensions.
178%
Guido van Rossumbd49ac41997-12-10 23:05:53 +0000179\item[\code{(?iLmsx)}] (One or more letters from the set 'i', 'L', 'm', 's',
Guido van Rossum0b334101997-12-08 17:33:40 +0000180'x'.) The group matches the empty string; the letters set the
181corresponding flags (re.I, re.L, re.M, re.S, re.X) for the entire regular
Guido van Rossum48d04371997-12-11 20:19:08 +0000182expression. This is useful if you wish include the flags as part of
183the regular expression, instead of passing a \var{flag} argument to
184the \code{compile} function.
Guido van Rossum0b334101997-12-08 17:33:40 +0000185%
Guido van Rossum1acceb01997-08-14 23:12:18 +0000186\item[\code{(?:...)}] A non-grouping version of regular parentheses.
187Matches whatever's inside the parentheses, but the text matched by the
188group \emph{cannot} be retrieved after performing a match or
189referenced later in the pattern.
190%
191\item[\code{(?P<\var{name}>...)}] Similar to regular parentheses, but
192the text matched by the group is accessible via the symbolic group
193name \var{name}. Group names must be valid Python identifiers. A
194symbolic group is also a numbered group, just as if the group were not
195named. So the group named 'id' in the example above can also be
196referenced as the numbered group 1.
197
Guido van Rossum48d04371997-12-11 20:19:08 +0000198For example, if the pattern is
199\code{(?P<id>[a-zA-Z_]\e w*)}, the group can be referenced by its
Guido van Rossum1acceb01997-08-14 23:12:18 +0000200name in arguments to methods of match objects, such as \code{m.group('id')}
201or \code{m.end('id')}, and also by name in pattern text (e.g. \code{(?P=id)}) and
202replacement text (e.g. \code{\e g<id>}).
203%
Guido van Rossum48d04371997-12-11 20:19:08 +0000204\item[\code{(?P=\var{name})}] Matches whatever text was matched by the earlier group named \var{name}.
205%
Guido van Rossum1acceb01997-08-14 23:12:18 +0000206\item[\code{(?\#...)}] A comment; the contents of the parentheses are simply ignored.
207%
Guido van Rossum0b334101997-12-08 17:33:40 +0000208\item[\code{(?=...)}] Matches if \code{...} matches next, but doesn't consume any of the string. This is called a lookahead assertion. For example,
209\code{Isaac (?=Asimov)} will match 'Isaac~' only if it's followed by 'Asimov'.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000210%
Guido van Rossum0b334101997-12-08 17:33:40 +0000211\item[\code{(?!...)}] Matches if \code{...} doesn't match next. This is a negative lookahead assertion. For example,
212For example,
213\code{Isaac (?!Asimov)} will match 'Isaac~' only if it's \emph{not} followed by 'Asimov'.
214
Guido van Rossum1acceb01997-08-14 23:12:18 +0000215\end{itemize}
216
217The special sequences consist of '\code{\e}' and a character from the
218list below. If the ordinary character is not on the list, then the
219resulting RE will match the second character. For example,
Guido van Rossum48d04371997-12-11 20:19:08 +0000220\code{\e\$} matches the character '\$'.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000221
222\begin{itemize}
223
224%
225\item[\code{\e \var{number}}] Matches the contents of the group of the
Guido van Rossum0b334101997-12-08 17:33:40 +0000226same number. Groups are numbered starting from 1. For example,
227\code{(.+) \e 1} matches 'the the' or '55 55', but not 'the end' (note
228the space after the group). This special sequence can only be used to
229match one of the first 99 groups. If the first digit of \var{number}
230is 0, or \var{number} is 3 octal digits long, it will not be interpreted
231as a group match, but as the character with octal value \var{number}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000232%
233\item[\code{\e A}] Matches only at the start of the string.
234%
235\item[\code{\e b}] Matches the empty string, but only at the
236beginning or end of a word. A word is defined as a sequence of
237alphanumeric characters, so the end of a word is indicated by
Guido van Rossum48d04371997-12-11 20:19:08 +0000238whitespace or a non-alphanumeric character. Inside a character range,
239\code{\e b} represents the backspace character, for compatibility with
240Python's string literals.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000241%
Guido van Rossum0b334101997-12-08 17:33:40 +0000242\item[\code{\e B}] Matches the empty string, but only when it is
243\emph{not} at the beginning or end of a word.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000244%
245\item[\code{\e d}]Matches any decimal digit; this is
246equivalent to the set \code{[0-9]}.
247%
248\item[\code{\e D}]Matches any non-digit character; this is
Fred Drake78f8e981997-12-29 21:39:39 +0000249equivalent to the set \code{[\^0-9]}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000250%
251\item[\code{\e s}]Matches any whitespace character; this is
252equivalent to the set \code{[ \e t\e n\e r\e f\e v]}.
253%
254\item[\code{\e S}]Matches any non-whitespace character; this is
Fred Drake78f8e981997-12-29 21:39:39 +0000255equivalent to the set \code{[\^ \e t\e n\e r\e f\e v]}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000256%
Guido van Rossum0b334101997-12-08 17:33:40 +0000257\item[\code{\e w}]When the LOCALE flag is not specified, matches any alphanumeric character; this is
258equivalent to the set \code{[a-zA-Z0-9_]}. With LOCALE, it will match
259the set \code{[0-9_]} plus whatever characters are defined as letters
260for the current locale.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000261%
Guido van Rossum0b334101997-12-08 17:33:40 +0000262\item[\code{\e W}]When the LOCALE flag is not specified, matches any
263non-alphanumeric character; this is equivalent to the set
Fred Drake78f8e981997-12-29 21:39:39 +0000264\code{[\^a-zA-Z0-9_]}. With LOCALE, it will match any character
Guido van Rossum0b334101997-12-08 17:33:40 +0000265not in the set \code{[0-9_]}, and not defined as a letter
266for the current locale.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000267
268\item[\code{\e Z}]Matches only at the end of the string.
269%
270
271\item[\code{\e \e}] Matches a literal backslash.
272
273\end{itemize}
274
275\subsection{Module Contents}
Fred Drake78f8e981997-12-29 21:39:39 +0000276\nodename{Contents of Module re}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000277
278The module defines the following functions and constants, and an exception:
279
280\renewcommand{\indexsubitem}{(in module re)}
281
282\begin{funcdesc}{compile}{pattern\optional{\, flags}}
283 Compile a regular expression pattern into a regular expression
284 object, which can be used for matching using its \code{match} and
285 \code{search} methods, described below.
286
Guido van Rossum0b334101997-12-08 17:33:40 +0000287 The expression's behaviour can be modified by specifying a
288 \var{flags} value. Values can be any of the following variables,
289 combined using bitwise OR (the \code{|} operator).
290
Fred Drake78f8e981997-12-29 21:39:39 +0000291\begin{description}
Guido van Rossum0b334101997-12-08 17:33:40 +0000292
Fred Drake78f8e981997-12-29 21:39:39 +0000293% The use of \quad in the item labels is ugly but adds enough space
294% to the label that it doesn't get visually run-in with the text.
Guido van Rossum0b334101997-12-08 17:33:40 +0000295
Fred Drake78f8e981997-12-29 21:39:39 +0000296\item[I or IGNORECASE or \code{(?i)}\quad]
297
298Perform case-insensitive matching; expressions like \code{[A-Z]} will match
Guido van Rossum48d04371997-12-11 20:19:08 +0000299lowercase letters, too. This is not affected by the current locale.
Guido van Rossum0b334101997-12-08 17:33:40 +0000300
Fred Drake78f8e981997-12-29 21:39:39 +0000301\item[L or LOCALE or \code{(?L)}\quad]
302
303Make \code{\e w}, \code{\e W}, \code{\e b},
Guido van Rossum48d04371997-12-11 20:19:08 +0000304\code{\e B}, dependent on the current locale.
Guido van Rossuma42c1781997-12-09 20:41:47 +0000305
Fred Drake78f8e981997-12-29 21:39:39 +0000306\item[M or MULTILINE or \code{(?m)}\quad]
Guido van Rossum48d04371997-12-11 20:19:08 +0000307
Fred Drake78f8e981997-12-29 21:39:39 +0000308When specified, the pattern character \code{\^} matches at the
Guido van Rossum48d04371997-12-11 20:19:08 +0000309 beginning of the string and at the beginning of each line
310 (immediately following each newline); and the pattern character
311\code{\$} matches at the end of the string and at the end of each line
312(immediately preceding each newline).
Guido van Rossum0b334101997-12-08 17:33:40 +0000313By default, \code{\^} matches only at the beginning of the string, and
314\code{\$} only at the end of the string and immediately before the
315newline (if any) at the end of the string.
Guido van Rossum0b334101997-12-08 17:33:40 +0000316
Fred Drake78f8e981997-12-29 21:39:39 +0000317\item[S or DOTALL or \code{(?s)}\quad]
Guido van Rossum0b334101997-12-08 17:33:40 +0000318
Fred Drake78f8e981997-12-29 21:39:39 +0000319Make the \code{.} special character any character at all, including a
Guido van Rossum48d04371997-12-11 20:19:08 +0000320newline; without this flag, \code{.} will match anything \emph{except}
Fred Drake78f8e981997-12-29 21:39:39 +0000321a newline.
Guido van Rossum48d04371997-12-11 20:19:08 +0000322
Fred Drake78f8e981997-12-29 21:39:39 +0000323\item[X or VERBOSE or \code{(?x)}\quad]
Guido van Rossum48d04371997-12-11 20:19:08 +0000324
Fred Drake78f8e981997-12-29 21:39:39 +0000325Ignore whitespace within the pattern
Guido van Rossum48d04371997-12-11 20:19:08 +0000326except when in a character class or preceded by an unescaped
327backslash, and, when a line contains a \code{\#} neither in a character
328class or preceded by an unescaped backslash, all characters from the
Fred Drake78f8e981997-12-29 21:39:39 +0000329leftmost such \code{\#} through the end of the line are ignored.
Guido van Rossum0b334101997-12-08 17:33:40 +0000330
Fred Drake78f8e981997-12-29 21:39:39 +0000331\end{description}
Guido van Rossum0b334101997-12-08 17:33:40 +0000332
Fred Drake78f8e981997-12-29 21:39:39 +0000333The sequence
Guido van Rossum1acceb01997-08-14 23:12:18 +0000334%
335\bcode\begin{verbatim}
336prog = re.compile(pat)
337result = prog.match(str)
338\end{verbatim}\ecode
339%
340is equivalent to
341%
342\bcode\begin{verbatim}
343result = re.match(pat, str)
344\end{verbatim}\ecode
345%
Guido van Rossum48d04371997-12-11 20:19:08 +0000346but the version using \code{compile()} is more efficient when the
347expression will be used several times in a single program.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000348%(The compiled version of the last pattern passed to \code{regex.match()} or
349%\code{regex.search()} is cached, so programs that use only a single
350%regular expression at a time needn't worry about compiling regular
351%expressions.)
352\end{funcdesc}
353
354\begin{funcdesc}{escape}{string}
Guido van Rossum48d04371997-12-11 20:19:08 +0000355 Return \var{string} with all non-alphanumerics backslashed; this is
356 useful if you want to match an arbitrary literal string that may have
357 regular expression metacharacters in it.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000358\end{funcdesc}
359
360\begin{funcdesc}{match}{pattern\, string\optional{\, flags}}
361 If zero or more characters at the beginning of \var{string} match
362 the regular expression \var{pattern}, return a corresponding
Guido van Rossum0148bbf1997-12-22 22:41:40 +0000363 \code{MatchObject} instance. Return \code{None} if the string does not
Guido van Rossum1acceb01997-08-14 23:12:18 +0000364 match the pattern; note that this is different from a zero-length
365 match.
366\end{funcdesc}
367
368\begin{funcdesc}{search}{pattern\, string\optional{\, flags}}
369 Scan through \var{string} looking for a location where the regular
Guido van Rossum0148bbf1997-12-22 22:41:40 +0000370 expression \var{pattern} produces a match, and return a corresponding \code{MatchObject} instance.
371 Return \code{None} if no
Guido van Rossum1acceb01997-08-14 23:12:18 +0000372 position in the string matches the pattern; note that this is
373 different from finding a zero-length match at some point in the string.
374\end{funcdesc}
375
376\begin{funcdesc}{split}{pattern\, string\, \optional{, maxsplit=0}}
377 Split \var{string} by the occurrences of \var{pattern}. If
378 capturing parentheses are used in pattern, then occurrences of
379 patterns or subpatterns are also returned.
380%
381\bcode\begin{verbatim}
382>>> re.split('[\W]+', 'Words, words, words.')
383['Words', 'words', 'words', '']
384>>> re.split('([\W]+)', 'Words, words, words.')
385['Words', ', ', 'words', ', ', 'words', '.', '']
386\end{verbatim}\ecode
387%
388 This function combines and extends the functionality of
Guido van Rossum0b334101997-12-08 17:33:40 +0000389 the old \code{regex.split()} and \code{regex.splitx()}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000390\end{funcdesc}
391
392\begin{funcdesc}{sub}{pattern\, repl\, string\optional{, count=0}}
393Return the string obtained by replacing the leftmost non-overlapping
394occurrences of \var{pattern} in \var{string} by the replacement
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000395\var{repl}. If the pattern isn't found, \var{string} is returned
396unchanged. \var{repl} can be a string or a function; if a function,
397it is called for every non-overlapping occurance of \var{pattern}.
Guido van Rossum0b334101997-12-08 17:33:40 +0000398The function takes a single match object argument, and returns the
399replacement string. For example:
Barry Warsaw4552f3d1997-11-20 00:15:13 +0000400%
401\bcode\begin{verbatim}
402>>> def dashrepl(matchobj):
403... if matchobj.group(0) == '-': return ' '
404... else: return '-'
405>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
406'pro--gram files'
407\end{verbatim}\ecode
408%
Guido van Rossum0b334101997-12-08 17:33:40 +0000409The pattern may be a string or a
Guido van Rossum48d04371997-12-11 20:19:08 +0000410regex object; if you need to specify
411regular expression flags, you must use a regex object, or use
412embedded modifiers in a pattern; e.g.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000413%
414\bcode\begin{verbatim}
415sub("(?i)b+", "x", "bbbb BBBB") returns 'x x'.
416\end{verbatim}\ecode
417%
418The optional argument \var{count} is the maximum number of pattern
419occurrences to be replaced; count must be a non-negative integer, and
420the default value of 0 means to replace all occurrences.
421
422Empty matches for the pattern are replaced only when not adjacent to a
423previous match, so \code{sub('x*', '-', 'abc')} returns '-a-b-c-'.
424\end{funcdesc}
425
426\begin{funcdesc}{subn}{pattern\, repl\, string\optional{, count=0}}
427Perform the same operation as \code{sub()}, but return a tuple
428\code{(new_string, number_of_subs_made)}.
429\end{funcdesc}
430
431\begin{excdesc}{error}
432 Exception raised when a string passed to one of the functions here
433 is not a valid regular expression (e.g., unmatched parentheses) or
434 when some other error occurs during compilation or matching. (It is
435 never an error if a string contains no match for a pattern.)
436\end{excdesc}
437
438\subsection{Regular Expression Objects}
439Compiled regular expression objects support the following methods and
440attributes:
441
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000442\renewcommand{\indexsubitem}{(re method)}
Guido van Rossum0b334101997-12-08 17:33:40 +0000443\begin{funcdesc}{match}{string\optional{\, pos}\optional{\, endpos}}
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000444 If zero or more characters at the beginning of \var{string} match
445 this regular expression, return a corresponding
Guido van Rossum48d04371997-12-11 20:19:08 +0000446 \code{MatchObject} instance. Return \code{None} if the string does not
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000447 match the pattern; note that this is different from a zero-length
448 match.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000449
450 The optional second parameter \var{pos} gives an index in the string
Guido van Rossum48d04371997-12-11 20:19:08 +0000451 where the search is to start; it defaults to \code{0}. The
452 \code{'\^'} pattern character will match at the index where the
453 search is to start.
Guido van Rossum0b334101997-12-08 17:33:40 +0000454
455 The optional parameter \var{endpos} limits how far the string will
456 be searched; it will be as if the string is \var{endpos} characters
457 long, so only the characters from \var{pos} to \var{endpos} will be
458 searched for a match.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000459\end{funcdesc}
460
Guido van Rossum0b334101997-12-08 17:33:40 +0000461\begin{funcdesc}{search}{string\optional{\, pos}\optional{\, endpos}}
Guido van Rossumeb53ae41997-10-05 18:54:07 +0000462 Scan through \var{string} looking for a location where this regular
463 expression produces a match. Return \code{None} if no
464 position in the string matches the pattern; note that this is
465 different from finding a zero-length match at some point in the string.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000466
Guido van Rossum48d04371997-12-11 20:19:08 +0000467 The optional \var{pos} and \var{endpos} parameters have the same
468 meaning as for the \code{match} method.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000469\end{funcdesc}
470
471\begin{funcdesc}{split}{string\, \optional{, maxsplit=0}}
472Identical to the \code{split} function, using the compiled pattern.
473\end{funcdesc}
474
475\begin{funcdesc}{sub}{repl\, string\optional{, count=0}}
476Identical to the \code{sub} function, using the compiled pattern.
477\end{funcdesc}
478
479\begin{funcdesc}{subn}{repl\, string\optional{, count=0}}
480Identical to the \code{subn} function, using the compiled pattern.
481\end{funcdesc}
482
483\renewcommand{\indexsubitem}{(regex attribute)}
484
485\begin{datadesc}{flags}
486The flags argument used when the regex object was compiled, or 0 if no
487flags were provided.
488\end{datadesc}
489
490\begin{datadesc}{groupindex}
491A dictionary mapping any symbolic group names (defined by
492\code{?P<\var{id}>}) to group numbers. The dictionary is empty if no
493symbolic groups were used in the pattern.
494\end{datadesc}
495
496\begin{datadesc}{pattern}
497The pattern string from which the regex object was compiled.
498\end{datadesc}
499
Guido van Rossum48d04371997-12-11 20:19:08 +0000500\subsection{MatchObjects}
501\code{Matchobject} instances support the following methods and attributes:
Guido van Rossum1acceb01997-08-14 23:12:18 +0000502
Guido van Rossum48d04371997-12-11 20:19:08 +0000503\begin{funcdesc}{group}{\optional{g1, g2, ...}}
504Returns one or more groups of the match. If there is a single
505\var{index} argument, the result is a single string; if there are
506multiple arguments, the result is a tuple with one item per argument.
507If the \var{index} is zero, the corresponding return value is the
508entire matching string; if it is in the inclusive range [1..99], it is
509the string matching the the corresponding parenthesized group. If no
510such group exists, the corresponding result is
511\code{None}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000512
Guido van Rossum0b334101997-12-08 17:33:40 +0000513If the regular expression uses the \code{(?P<\var{name}>...)} syntax,
514the \var{index} arguments may also be strings identifying groups by
515their group name.
Guido van Rossume4eb2231997-12-17 00:23:39 +0000516
517A moderately complicated example:
518\bcode\begin{verbatim}
519m = re.match(r"(?P<int>\d+)\.(\d*)", '3.14')
520\end{verbatim}\ecode
521%
522After performing this match, \code{m.group(1)} is \code{'3'}, as is \code{m.group('int')}.
523\code{m.group(2)} is \code{'14'}.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000524\end{funcdesc}
525
Guido van Rossum48d04371997-12-11 20:19:08 +0000526\begin{funcdesc}{groups}{}
527Return a tuple containing all the subgroups of the match, from 1 up to
528however many groups are in the pattern. Groups that did not
529participate in the match have values of \code{None}. If the tuple
530would only be one element long, a string will be returned instead.
531\end{funcdesc}
532
Guido van Rossume4eb2231997-12-17 00:23:39 +0000533\begin{funcdesc}{start}{group}
534\end{funcdesc}
535
536\begin{funcdesc}{end}{group}
537Return the indices of the start and end of the substring
538matched by \var{group}. Return \code{None} if \var{group} exists but
539did not contribute to the match. For a match object
540\code{m}, and a group \code{g} that did contribute to the match, the
541substring matched by group \code{g} (equivalent to \code{m.group(g)}) is
542\bcode\begin{verbatim}
543 m.string[m.start(g):m.end(g)]
544\end{verbatim}\ecode
545%
546Note that
547\code{m.start(\var{group})} will equal \code{m.end(\var{group})} if
548\var{group} matched a null string. For example, after \code{m =
549re.search('b(c?)', 'cba')}, \code{m.start(0)} is 1, \code{m.end(0)} is
5502, \code{m.start(1)} and \code{m.end(1)} are both 2, and
551\code{m.start(2)} raises an \code{IndexError} exception.
552
553\end{funcdesc}
554
555\begin{funcdesc}{span}{group}
556Return the 2-tuple \code{(start(\var{group}), end(\var{group}))}.
557Note that if \var{group} did not contribute to the match, this is
558\code{(None, None)}.
559\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
563\code{search} or \code{match} function. This is the index into the
564string at which the regex engine started looking for a match.
565\end{datadesc}
566
567\begin{datadesc}{endpos}
568The value of \var{endpos} which was passed to the
569\code{search} or \code{match} function. This is the index into the
570string beyond which the regex engine will not go.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000571\end{datadesc}
572
573\begin{datadesc}{re}
Guido van Rossum48d04371997-12-11 20:19:08 +0000574The regular expression object whose \code{match()} or \code{search()} method
575produced this \code{MatchObject} instance.
Guido van Rossum1acceb01997-08-14 23:12:18 +0000576\end{datadesc}
577
578\begin{datadesc}{string}
579The string passed to \code{match()} or \code{search()}.
580\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},
Guido van Rossume4eb2231997-12-17 00:23:39 +0000584O'Reilly. The Python material in this book dates from before the re
585module, but it covers writing good regular expression patterns in
Fred Drakef9951811997-12-29 16:37:04 +0000586great detail.}
Guido van Rossum1acceb01997-08-14 23:12:18 +0000587\end{seealso}
Guido van Rossume4eb2231997-12-17 00:23:39 +0000588
589