blob: 62b6dafb78f846ddaa521c5e81905ac249e4b5ac [file] [log] [blame]
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +00001\documentclass{howto}
2
3% TODO:
4% Document lookbehind assertions
5% Better way of displaying a RE, a string, and what it matches
6% Mention optional argument to match.groups()
7% Unicode (at least a reference)
8
9\title{Regular Expression HOWTO}
10
11\release{0.05}
12
13\author{A.M. Kuchling}
14\authoraddress{\email{amk@amk.ca}}
15
16\begin{document}
17\maketitle
18
19\begin{abstract}
20\noindent
21This document is an introductory tutorial to using regular expressions
22in Python with the \module{re} module. It provides a gentler
23introduction than the corresponding section in the Library Reference.
24
25This document is available from
26\url{http://www.amk.ca/python/howto}.
27
28\end{abstract}
29
30\tableofcontents
31
32\section{Introduction}
33
34The \module{re} module was added in Python 1.5, and provides
35Perl-style regular expression patterns. Earlier versions of Python
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000036came with the \module{regex} module, which provided Emacs-style
Thomas Wouters9fe394c2007-02-05 01:24:16 +000037patterns. The \module{regex} module was removed completely in Python 2.5.
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +000038
Thomas Wouters9fe394c2007-02-05 01:24:16 +000039Regular expressions (called REs, or regexes, or regex patterns) are
40essentially a tiny, highly specialized programming language embedded
41inside Python and made available through the \module{re} module.
42Using this little language, you specify the rules for the set of
43possible strings that you want to match; this set might contain
44English sentences, or e-mail addresses, or TeX commands, or anything
45you like. You can then ask questions such as ``Does this string match
46the pattern?'', or ``Is there a match for the pattern anywhere in this
47string?''. You can also use REs to modify a string or to split it
48apart in various ways.
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +000049
50Regular expression patterns are compiled into a series of bytecodes
51which are then executed by a matching engine written in C. For
52advanced use, it may be necessary to pay careful attention to how the
53engine will execute a given RE, and write the RE in a certain way in
54order to produce bytecode that runs faster. Optimization isn't
55covered in this document, because it requires that you have a good
56understanding of the matching engine's internals.
57
58The regular expression language is relatively small and restricted, so
59not all possible string processing tasks can be done using regular
60expressions. There are also tasks that \emph{can} be done with
61regular expressions, but the expressions turn out to be very
62complicated. In these cases, you may be better off writing Python
63code to do the processing; while Python code will be slower than an
64elaborate regular expression, it will also probably be more understandable.
65
66\section{Simple Patterns}
67
68We'll start by learning about the simplest possible regular
69expressions. Since regular expressions are used to operate on
70strings, we'll begin with the most common task: matching characters.
71
72For a detailed explanation of the computer science underlying regular
73expressions (deterministic and non-deterministic finite automata), you
74can refer to almost any textbook on writing compilers.
75
76\subsection{Matching Characters}
77
78Most letters and characters will simply match themselves. For
79example, the regular expression \regexp{test} will match the string
80\samp{test} exactly. (You can enable a case-insensitive mode that
81would let this RE match \samp{Test} or \samp{TEST} as well; more
82about this later.)
83
Thomas Wouters9fe394c2007-02-05 01:24:16 +000084There are exceptions to this rule; some characters are special
85\dfn{metacharacters}, and don't match themselves. Instead, they
86signal that some out-of-the-ordinary thing should be matched, or they
87affect other portions of the RE by repeating them or changing their
88meaning. Much of this document is devoted to discussing various
89metacharacters and what they do.
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +000090
91Here's a complete list of the metacharacters; their meanings will be
92discussed in the rest of this HOWTO.
93
94\begin{verbatim}
95. ^ $ * + ? { [ ] \ | ( )
96\end{verbatim}
97% $
98
99The first metacharacters we'll look at are \samp{[} and \samp{]}.
100They're used for specifying a character class, which is a set of
101characters that you wish to match. Characters can be listed
102individually, or a range of characters can be indicated by giving two
103characters and separating them by a \character{-}. For example,
104\regexp{[abc]} will match any of the characters \samp{a}, \samp{b}, or
105\samp{c}; this is the same as
106\regexp{[a-c]}, which uses a range to express the same set of
107characters. If you wanted to match only lowercase letters, your
108RE would be \regexp{[a-z]}.
109
110Metacharacters are not active inside classes. For example,
111\regexp{[akm\$]} will match any of the characters \character{a},
112\character{k}, \character{m}, or \character{\$}; \character{\$} is
113usually a metacharacter, but inside a character class it's stripped of
114its special nature.
115
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000116You can match the characters not listed within the class by
117\dfn{complementing} the set. This is indicated by including a
118\character{\^} as the first character of the class; \character{\^}
119outside a character class will simply match the
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000120\character{\^} character. For example, \verb|[^5]| will match any
121character except \character{5}.
122
123Perhaps the most important metacharacter is the backslash, \samp{\e}.
124As in Python string literals, the backslash can be followed by various
125characters to signal various special sequences. It's also used to escape
126all the metacharacters so you can still match them in patterns; for
127example, if you need to match a \samp{[} or
128\samp{\e}, you can precede them with a backslash to remove their
129special meaning: \regexp{\e[} or \regexp{\e\e}.
130
131Some of the special sequences beginning with \character{\e} represent
132predefined sets of characters that are often useful, such as the set
133of digits, the set of letters, or the set of anything that isn't
134whitespace. The following predefined special sequences are available:
135
136\begin{itemize}
137\item[\code{\e d}]Matches any decimal digit; this is
138equivalent to the class \regexp{[0-9]}.
139
140\item[\code{\e D}]Matches any non-digit character; this is
141equivalent to the class \verb|[^0-9]|.
142
143\item[\code{\e s}]Matches any whitespace character; this is
144equivalent to the class \regexp{[ \e t\e n\e r\e f\e v]}.
145
146\item[\code{\e S}]Matches any non-whitespace character; this is
147equivalent to the class \verb|[^ \t\n\r\f\v]|.
148
149\item[\code{\e w}]Matches any alphanumeric character; this is equivalent to the class
150\regexp{[a-zA-Z0-9_]}.
151
152\item[\code{\e W}]Matches any non-alphanumeric character; this is equivalent to the class
153\verb|[^a-zA-Z0-9_]|.
154\end{itemize}
155
156These sequences can be included inside a character class. For
157example, \regexp{[\e s,.]} is a character class that will match any
158whitespace character, or \character{,} or \character{.}.
159
160The final metacharacter in this section is \regexp{.}. It matches
161anything except a newline character, and there's an alternate mode
162(\code{re.DOTALL}) where it will match even a newline. \character{.}
163is often used where you want to match ``any character''.
164
165\subsection{Repeating Things}
166
167Being able to match varying sets of characters is the first thing
168regular expressions can do that isn't already possible with the
169methods available on strings. However, if that was the only
170additional capability of regexes, they wouldn't be much of an advance.
171Another capability is that you can specify that portions of the RE
172must be repeated a certain number of times.
173
174The first metacharacter for repeating things that we'll look at is
175\regexp{*}. \regexp{*} doesn't match the literal character \samp{*};
176instead, it specifies that the previous character can be matched zero
177or more times, instead of exactly once.
178
179For example, \regexp{ca*t} will match \samp{ct} (0 \samp{a}
180characters), \samp{cat} (1 \samp{a}), \samp{caaat} (3 \samp{a}
181characters), and so forth. The RE engine has various internal
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000182limitations stemming from the size of C's \code{int} type that will
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000183prevent it from matching over 2 billion \samp{a} characters; you
184probably don't have enough memory to construct a string that large, so
185you shouldn't run into that limit.
186
187Repetitions such as \regexp{*} are \dfn{greedy}; when repeating a RE,
188the matching engine will try to repeat it as many times as possible.
189If later portions of the pattern don't match, the matching engine will
190then back up and try again with few repetitions.
191
192A step-by-step example will make this more obvious. Let's consider
193the expression \regexp{a[bcd]*b}. This matches the letter
194\character{a}, zero or more letters from the class \code{[bcd]}, and
195finally ends with a \character{b}. Now imagine matching this RE
196against the string \samp{abcbd}.
197
198\begin{tableiii}{c|l|l}{}{Step}{Matched}{Explanation}
199\lineiii{1}{\code{a}}{The \regexp{a} in the RE matches.}
200\lineiii{2}{\code{abcbd}}{The engine matches \regexp{[bcd]*}, going as far as
201it can, which is to the end of the string.}
202\lineiii{3}{\emph{Failure}}{The engine tries to match \regexp{b}, but the
203current position is at the end of the string, so it fails.}
204\lineiii{4}{\code{abcb}}{Back up, so that \regexp{[bcd]*} matches
205one less character.}
206\lineiii{5}{\emph{Failure}}{Try \regexp{b} again, but the
207current position is at the last character, which is a \character{d}.}
208\lineiii{6}{\code{abc}}{Back up again, so that \regexp{[bcd]*} is
209only matching \samp{bc}.}
210\lineiii{6}{\code{abcb}}{Try \regexp{b} again. This time
211but the character at the current position is \character{b}, so it succeeds.}
212\end{tableiii}
213
214The end of the RE has now been reached, and it has matched
215\samp{abcb}. This demonstrates how the matching engine goes as far as
216it can at first, and if no match is found it will then progressively
217back up and retry the rest of the RE again and again. It will back up
218until it has tried zero matches for \regexp{[bcd]*}, and if that
219subsequently fails, the engine will conclude that the string doesn't
220match the RE at all.
221
222Another repeating metacharacter is \regexp{+}, which matches one or
223more times. Pay careful attention to the difference between
224\regexp{*} and \regexp{+}; \regexp{*} matches \emph{zero} or more
225times, so whatever's being repeated may not be present at all, while
226\regexp{+} requires at least \emph{one} occurrence. To use a similar
227example, \regexp{ca+t} will match \samp{cat} (1 \samp{a}),
228\samp{caaat} (3 \samp{a}'s), but won't match \samp{ct}.
229
230There are two more repeating qualifiers. The question mark character,
231\regexp{?}, matches either once or zero times; you can think of it as
232marking something as being optional. For example, \regexp{home-?brew}
233matches either \samp{homebrew} or \samp{home-brew}.
234
235The most complicated repeated qualifier is
236\regexp{\{\var{m},\var{n}\}}, where \var{m} and \var{n} are decimal
237integers. This qualifier means there must be at least \var{m}
238repetitions, and at most \var{n}. For example, \regexp{a/\{1,3\}b}
239will match \samp{a/b}, \samp{a//b}, and \samp{a///b}. It won't match
240\samp{ab}, which has no slashes, or \samp{a////b}, which has four.
241
242You can omit either \var{m} or \var{n}; in that case, a reasonable
243value is assumed for the missing value. Omitting \var{m} is
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000244interpreted as a lower limit of 0, while omitting \var{n} results in
245an upper bound of infinity --- actually, the upper bound is the
2462-billion limit mentioned earlier, but that might as well be infinity.
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000247
248Readers of a reductionist bent may notice that the three other qualifiers
249can all be expressed using this notation. \regexp{\{0,\}} is the same
250as \regexp{*}, \regexp{\{1,\}} is equivalent to \regexp{+}, and
251\regexp{\{0,1\}} is the same as \regexp{?}. It's better to use
252\regexp{*}, \regexp{+}, or \regexp{?} when you can, simply because
253they're shorter and easier to read.
254
255\section{Using Regular Expressions}
256
257Now that we've looked at some simple regular expressions, how do we
258actually use them in Python? The \module{re} module provides an
259interface to the regular expression engine, allowing you to compile
260REs into objects and then perform matches with them.
261
262\subsection{Compiling Regular Expressions}
263
264Regular expressions are compiled into \class{RegexObject} instances,
265which have methods for various operations such as searching for
266pattern matches or performing string substitutions.
267
268\begin{verbatim}
269>>> import re
270>>> p = re.compile('ab*')
271>>> print p
272<re.RegexObject instance at 80b4150>
273\end{verbatim}
274
275\function{re.compile()} also accepts an optional \var{flags}
276argument, used to enable various special features and syntax
277variations. We'll go over the available settings later, but for now a
278single example will do:
279
280\begin{verbatim}
281>>> p = re.compile('ab*', re.IGNORECASE)
282\end{verbatim}
283
284The RE is passed to \function{re.compile()} as a string. REs are
285handled as strings because regular expressions aren't part of the core
286Python language, and no special syntax was created for expressing
287them. (There are applications that don't need REs at all, so there's
288no need to bloat the language specification by including them.)
289Instead, the \module{re} module is simply a C extension module
290included with Python, just like the \module{socket} or \module{zlib}
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000291modules.
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000292
293Putting REs in strings keeps the Python language simpler, but has one
294disadvantage which is the topic of the next section.
295
296\subsection{The Backslash Plague}
297
298As stated earlier, regular expressions use the backslash
299character (\character{\e}) to indicate special forms or to allow
300special characters to be used without invoking their special meaning.
301This conflicts with Python's usage of the same character for the same
302purpose in string literals.
303
304Let's say you want to write a RE that matches the string
305\samp{{\e}section}, which might be found in a \LaTeX\ file. To figure
306out what to write in the program code, start with the desired string
307to be matched. Next, you must escape any backslashes and other
308metacharacters by preceding them with a backslash, resulting in the
309string \samp{\e\e section}. The resulting string that must be passed
310to \function{re.compile()} must be \verb|\\section|. However, to
311express this as a Python string literal, both backslashes must be
312escaped \emph{again}.
313
314\begin{tableii}{c|l}{code}{Characters}{Stage}
315 \lineii{\e section}{Text string to be matched}
316 \lineii{\e\e section}{Escaped backslash for \function{re.compile}}
317 \lineii{"\e\e\e\e section"}{Escaped backslashes for a string literal}
318\end{tableii}
319
320In short, to match a literal backslash, one has to write
321\code{'\e\e\e\e'} as the RE string, because the regular expression
322must be \samp{\e\e}, and each backslash must be expressed as
323\samp{\e\e} inside a regular Python string literal. In REs that
324feature backslashes repeatedly, this leads to lots of repeated
325backslashes and makes the resulting strings difficult to understand.
326
327The solution is to use Python's raw string notation for regular
328expressions; backslashes are not handled in any special way in
329a string literal prefixed with \character{r}, so \code{r"\e n"} is a
330two-character string containing \character{\e} and \character{n},
331while \code{"\e n"} is a one-character string containing a newline.
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000332Regular expressions will often be written in Python
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000333code using this raw string notation.
334
335\begin{tableii}{c|c}{code}{Regular String}{Raw string}
336 \lineii{"ab*"}{\code{r"ab*"}}
337 \lineii{"\e\e\e\e section"}{\code{r"\e\e section"}}
338 \lineii{"\e\e w+\e\e s+\e\e 1"}{\code{r"\e w+\e s+\e 1"}}
339\end{tableii}
340
341\subsection{Performing Matches}
342
343Once you have an object representing a compiled regular expression,
344what do you do with it? \class{RegexObject} instances have several
345methods and attributes. Only the most significant ones will be
346covered here; consult \ulink{the Library
347Reference}{http://www.python.org/doc/lib/module-re.html} for a
348complete listing.
349
350\begin{tableii}{c|l}{code}{Method/Attribute}{Purpose}
351 \lineii{match()}{Determine if the RE matches at the beginning of
352 the string.}
353 \lineii{search()}{Scan through a string, looking for any location
354 where this RE matches.}
355 \lineii{findall()}{Find all substrings where the RE matches,
356and returns them as a list.}
357 \lineii{finditer()}{Find all substrings where the RE matches,
358and returns them as an iterator.}
359\end{tableii}
360
361\method{match()} and \method{search()} return \code{None} if no match
362can be found. If they're successful, a \code{MatchObject} instance is
363returned, containing information about the match: where it starts and
364ends, the substring it matched, and more.
365
366You can learn about this by interactively experimenting with the
367\module{re} module. If you have Tkinter available, you may also want
368to look at \file{Tools/scripts/redemo.py}, a demonstration program
369included with the Python distribution. It allows you to enter REs and
370strings, and displays whether the RE matches or fails.
371\file{redemo.py} can be quite useful when trying to debug a
372complicated RE. Phil Schwartz's
Thomas Wouters89f507f2006-12-13 04:49:30 +0000373\ulink{Kodos}{http://www.phil-schwartz.com/kodos.spy} is also an interactive
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000374tool for developing and testing RE patterns.
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000375
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000376This HOWTO uses the standard Python interpreter for its examples.
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000377First, run the Python interpreter, import the \module{re} module, and
378compile a RE:
379
380\begin{verbatim}
381Python 2.2.2 (#1, Feb 10 2003, 12:57:01)
382>>> import re
383>>> p = re.compile('[a-z]+')
384>>> p
385<_sre.SRE_Pattern object at 80c3c28>
386\end{verbatim}
387
388Now, you can try matching various strings against the RE
389\regexp{[a-z]+}. An empty string shouldn't match at all, since
390\regexp{+} means 'one or more repetitions'. \method{match()} should
391return \code{None} in this case, which will cause the interpreter to
392print no output. You can explicitly print the result of
393\method{match()} to make this clear.
394
395\begin{verbatim}
396>>> p.match("")
397>>> print p.match("")
398None
399\end{verbatim}
400
401Now, let's try it on a string that it should match, such as
402\samp{tempo}. In this case, \method{match()} will return a
403\class{MatchObject}, so you should store the result in a variable for
404later use.
405
406\begin{verbatim}
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000407>>> m = p.match('tempo')
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000408>>> print m
409<_sre.SRE_Match object at 80c4f68>
410\end{verbatim}
411
412Now you can query the \class{MatchObject} for information about the
413matching string. \class{MatchObject} instances also have several
414methods and attributes; the most important ones are:
415
416\begin{tableii}{c|l}{code}{Method/Attribute}{Purpose}
417 \lineii{group()}{Return the string matched by the RE}
418 \lineii{start()}{Return the starting position of the match}
419 \lineii{end()}{Return the ending position of the match}
420 \lineii{span()}{Return a tuple containing the (start, end) positions
421 of the match}
422\end{tableii}
423
424Trying these methods will soon clarify their meaning:
425
426\begin{verbatim}
427>>> m.group()
428'tempo'
429>>> m.start(), m.end()
430(0, 5)
431>>> m.span()
432(0, 5)
433\end{verbatim}
434
435\method{group()} returns the substring that was matched by the
436RE. \method{start()} and \method{end()} return the starting and
437ending index of the match. \method{span()} returns both start and end
438indexes in a single tuple. Since the \method{match} method only
439checks if the RE matches at the start of a string,
440\method{start()} will always be zero. However, the \method{search}
441method of \class{RegexObject} instances scans through the string, so
442the match may not start at zero in that case.
443
444\begin{verbatim}
445>>> print p.match('::: message')
446None
447>>> m = p.search('::: message') ; print m
448<re.MatchObject instance at 80c9650>
449>>> m.group()
450'message'
451>>> m.span()
452(4, 11)
453\end{verbatim}
454
455In actual programs, the most common style is to store the
456\class{MatchObject} in a variable, and then check if it was
457\code{None}. This usually looks like:
458
459\begin{verbatim}
460p = re.compile( ... )
461m = p.match( 'string goes here' )
462if m:
463 print 'Match found: ', m.group()
464else:
465 print 'No match'
466\end{verbatim}
467
468Two \class{RegexObject} methods return all of the matches for a pattern.
469\method{findall()} returns a list of matching strings:
470
471\begin{verbatim}
472>>> p = re.compile('\d+')
473>>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
474['12', '11', '10']
475\end{verbatim}
476
477\method{findall()} has to create the entire list before it can be
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000478returned as the result. The \method{finditer()} method returns a
479sequence of \class{MatchObject} instances as an
480iterator.\footnote{Introduced in Python 2.2.2.}
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000481
482\begin{verbatim}
483>>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
484>>> iterator
485<callable-iterator object at 0x401833ac>
486>>> for match in iterator:
487... print match.span()
488...
489(0, 2)
490(22, 24)
491(29, 31)
492\end{verbatim}
493
494
495\subsection{Module-Level Functions}
496
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000497You don't have to create a \class{RegexObject} and call its methods;
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000498the \module{re} module also provides top-level functions called
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000499\function{match()}, \function{search()}, \function{findall()},
500\function{sub()}, and so forth. These functions take the same
501arguments as the corresponding \class{RegexObject} method, with the RE
502string added as the first argument, and still return either
503\code{None} or a \class{MatchObject} instance.
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000504
505\begin{verbatim}
506>>> print re.match(r'From\s+', 'Fromage amk')
507None
508>>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998')
509<re.MatchObject instance at 80c5978>
510\end{verbatim}
511
512Under the hood, these functions simply produce a \class{RegexObject}
513for you and call the appropriate method on it. They also store the
514compiled object in a cache, so future calls using the same
515RE are faster.
516
517Should you use these module-level functions, or should you get the
518\class{RegexObject} and call its methods yourself? That choice
519depends on how frequently the RE will be used, and on your personal
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000520coding style. If the RE is being used at only one point in the code,
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000521then the module functions are probably more convenient. If a program
522contains a lot of regular expressions, or re-uses the same ones in
523several locations, then it might be worthwhile to collect all the
524definitions in one place, in a section of code that compiles all the
525REs ahead of time. To take an example from the standard library,
526here's an extract from \file{xmllib.py}:
527
528\begin{verbatim}
529ref = re.compile( ... )
530entityref = re.compile( ... )
531charref = re.compile( ... )
532starttagopen = re.compile( ... )
533\end{verbatim}
534
535I generally prefer to work with the compiled object, even for
536one-time uses, but few people will be as much of a purist about this
537as I am.
538
539\subsection{Compilation Flags}
540
541Compilation flags let you modify some aspects of how regular
542expressions work. Flags are available in the \module{re} module under
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000543two names, a long name such as \constant{IGNORECASE} and a short,
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000544one-letter form such as \constant{I}. (If you're familiar with Perl's
545pattern modifiers, the one-letter forms use the same letters; the
546short form of \constant{re.VERBOSE} is \constant{re.X}, for example.)
547Multiple flags can be specified by bitwise OR-ing them; \code{re.I |
548re.M} sets both the \constant{I} and \constant{M} flags, for example.
549
550Here's a table of the available flags, followed by
551a more detailed explanation of each one.
552
553\begin{tableii}{c|l}{}{Flag}{Meaning}
554 \lineii{\constant{DOTALL}, \constant{S}}{Make \regexp{.} match any
555 character, including newlines}
556 \lineii{\constant{IGNORECASE}, \constant{I}}{Do case-insensitive matches}
557 \lineii{\constant{LOCALE}, \constant{L}}{Do a locale-aware match}
558 \lineii{\constant{MULTILINE}, \constant{M}}{Multi-line matching,
559 affecting \regexp{\^} and \regexp{\$}}
560 \lineii{\constant{VERBOSE}, \constant{X}}{Enable verbose REs,
561 which can be organized more cleanly and understandably.}
562\end{tableii}
563
564\begin{datadesc}{I}
565\dataline{IGNORECASE}
566Perform case-insensitive matching; character class and literal strings
567will match
568letters by ignoring case. For example, \regexp{[A-Z]} will match
569lowercase letters, too, and \regexp{Spam} will match \samp{Spam},
570\samp{spam}, or \samp{spAM}.
571This lowercasing doesn't take the current locale into account; it will
572if you also set the \constant{LOCALE} flag.
573\end{datadesc}
574
575\begin{datadesc}{L}
576\dataline{LOCALE}
577Make \regexp{\e w}, \regexp{\e W}, \regexp{\e b},
578and \regexp{\e B}, dependent on the current locale.
579
580Locales are a feature of the C library intended to help in writing
581programs that take account of language differences. For example, if
582you're processing French text, you'd want to be able to write
583\regexp{\e w+} to match words, but \regexp{\e w} only matches the
584character class \regexp{[A-Za-z]}; it won't match \character{\'e} or
585\character{\c c}. If your system is configured properly and a French
586locale is selected, certain C functions will tell the program that
587\character{\'e} should also be considered a letter. Setting the
588\constant{LOCALE} flag when compiling a regular expression will cause the
589resulting compiled object to use these C functions for \regexp{\e w};
590this is slower, but also enables \regexp{\e w+} to match French words as
591you'd expect.
592\end{datadesc}
593
594\begin{datadesc}{M}
595\dataline{MULTILINE}
596(\regexp{\^} and \regexp{\$} haven't been explained yet;
597they'll be introduced in section~\ref{more-metacharacters}.)
598
599Usually \regexp{\^} matches only at the beginning of the string, and
600\regexp{\$} matches only at the end of the string and immediately before the
601newline (if any) at the end of the string. When this flag is
602specified, \regexp{\^} matches at the beginning of the string and at
603the beginning of each line within the string, immediately following
604each newline. Similarly, the \regexp{\$} metacharacter matches either at
605the end of the string and at the end of each line (immediately
606preceding each newline).
607
608\end{datadesc}
609
610\begin{datadesc}{S}
611\dataline{DOTALL}
612Makes the \character{.} special character match any character at all,
613including a newline; without this flag, \character{.} will match
614anything \emph{except} a newline.
615\end{datadesc}
616
617\begin{datadesc}{X}
618\dataline{VERBOSE} This flag allows you to write regular expressions
619that are more readable by granting you more flexibility in how you can
620format them. When this flag has been specified, whitespace within the
621RE string is ignored, except when the whitespace is in a character
622class or preceded by an unescaped backslash; this lets you organize
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000623and indent the RE more clearly. This flag also lets you put comments
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000624within a RE that will be ignored by the engine; comments are marked by
625a \character{\#} that's neither in a character class or preceded by an
626unescaped backslash.
627
628For example, here's a RE that uses \constant{re.VERBOSE}; see how
629much easier it is to read?
630
631\begin{verbatim}
632charref = re.compile(r"""
633 &[#] # Start of a numeric entity reference
634 (
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000635 0[0-7]+ # Octal form
636 | [0-9]+ # Decimal form
637 | x[0-9a-fA-F]+ # Hexadecimal form
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000638 )
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000639 ; # Trailing semicolon
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000640""", re.VERBOSE)
641\end{verbatim}
642
643Without the verbose setting, the RE would look like this:
644\begin{verbatim}
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000645charref = re.compile("&#(0[0-7]+"
646 "|[0-9]+"
647 "|x[0-9a-fA-F]+);")
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000648\end{verbatim}
649
650In the above example, Python's automatic concatenation of string
651literals has been used to break up the RE into smaller pieces, but
652it's still more difficult to understand than the version using
653\constant{re.VERBOSE}.
654
655\end{datadesc}
656
657\section{More Pattern Power}
658
659So far we've only covered a part of the features of regular
660expressions. In this section, we'll cover some new metacharacters,
661and how to use groups to retrieve portions of the text that was matched.
662
663\subsection{More Metacharacters\label{more-metacharacters}}
664
665There are some metacharacters that we haven't covered yet. Most of
666them will be covered in this section.
667
668Some of the remaining metacharacters to be discussed are
669\dfn{zero-width assertions}. They don't cause the engine to advance
670through the string; instead, they consume no characters at all,
671and simply succeed or fail. For example, \regexp{\e b} is an
672assertion that the current position is located at a word boundary; the
673position isn't changed by the \regexp{\e b} at all. This means that
674zero-width assertions should never be repeated, because if they match
675once at a given location, they can obviously be matched an infinite
676number of times.
677
678\begin{list}{}{}
679
680\item[\regexp{|}]
681Alternation, or the ``or'' operator.
682If A and B are regular expressions,
683\regexp{A|B} will match any string that matches either \samp{A} or \samp{B}.
684\regexp{|} has very low precedence in order to make it work reasonably when
685you're alternating multi-character strings.
686\regexp{Crow|Servo} will match either \samp{Crow} or \samp{Servo}, not
687\samp{Cro}, a \character{w} or an \character{S}, and \samp{ervo}.
688
689To match a literal \character{|},
690use \regexp{\e|}, or enclose it inside a character class, as in \regexp{[|]}.
691
692\item[\regexp{\^}] Matches at the beginning of lines. Unless the
693\constant{MULTILINE} flag has been set, this will only match at the
694beginning of the string. In \constant{MULTILINE} mode, this also
695matches immediately after each newline within the string.
696
697For example, if you wish to match the word \samp{From} only at the
698beginning of a line, the RE to use is \verb|^From|.
699
700\begin{verbatim}
701>>> print re.search('^From', 'From Here to Eternity')
702<re.MatchObject instance at 80c1520>
703>>> print re.search('^From', 'Reciting From Memory')
704None
705\end{verbatim}
706
707%To match a literal \character{\^}, use \regexp{\e\^} or enclose it
708%inside a character class, as in \regexp{[{\e}\^]}.
709
710\item[\regexp{\$}] Matches at the end of a line, which is defined as
711either the end of the string, or any location followed by a newline
712character.
713
714\begin{verbatim}
715>>> print re.search('}$', '{block}')
716<re.MatchObject instance at 80adfa8>
717>>> print re.search('}$', '{block} ')
718None
719>>> print re.search('}$', '{block}\n')
720<re.MatchObject instance at 80adfa8>
721\end{verbatim}
722% $
723
724To match a literal \character{\$}, use \regexp{\e\$} or enclose it
725inside a character class, as in \regexp{[\$]}.
726
727\item[\regexp{\e A}] Matches only at the start of the string. When
728not in \constant{MULTILINE} mode, \regexp{\e A} and \regexp{\^} are
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000729effectively the same. In \constant{MULTILINE} mode, they're
730different: \regexp{\e A} still matches only at the beginning of the
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000731string, but \regexp{\^} may match at any location inside the string
732that follows a newline character.
733
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000734\item[\regexp{\e Z}] Matches only at the end of the string.
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000735
736\item[\regexp{\e b}] Word boundary.
737This is a zero-width assertion that matches only at the
738beginning or end of a word. A word is defined as a sequence of
739alphanumeric characters, so the end of a word is indicated by
740whitespace or a non-alphanumeric character.
741
742The following example matches \samp{class} only when it's a complete
743word; it won't match when it's contained inside another word.
744
745\begin{verbatim}
746>>> p = re.compile(r'\bclass\b')
747>>> print p.search('no class at all')
748<re.MatchObject instance at 80c8f28>
749>>> print p.search('the declassified algorithm')
750None
751>>> print p.search('one subclass is')
752None
753\end{verbatim}
754
755There are two subtleties you should remember when using this special
756sequence. First, this is the worst collision between Python's string
757literals and regular expression sequences. In Python's string
758literals, \samp{\e b} is the backspace character, ASCII value 8. If
759you're not using raw strings, then Python will convert the \samp{\e b} to
760a backspace, and your RE won't match as you expect it to. The
761following example looks the same as our previous RE, but omits
762the \character{r} in front of the RE string.
763
764\begin{verbatim}
765>>> p = re.compile('\bclass\b')
766>>> print p.search('no class at all')
767None
768>>> print p.search('\b' + 'class' + '\b')
769<re.MatchObject instance at 80c3ee0>
770\end{verbatim}
771
772Second, inside a character class, where there's no use for this
773assertion, \regexp{\e b} represents the backspace character, for
774compatibility with Python's string literals.
775
776\item[\regexp{\e B}] Another zero-width assertion, this is the
777opposite of \regexp{\e b}, only matching when the current
778position is not at a word boundary.
779
780\end{list}
781
782\subsection{Grouping}
783
784Frequently you need to obtain more information than just whether the
785RE matched or not. Regular expressions are often used to dissect
786strings by writing a RE divided into several subgroups which
787match different components of interest. For example, an RFC-822
788header line is divided into a header name and a value, separated by a
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000789\character{:}, like this:
790
791\begin{verbatim}
792From: author@example.com
793User-Agent: Thunderbird 1.5.0.9 (X11/20061227)
794MIME-Version: 1.0
795To: editor@example.com
796\end{verbatim}
797
798This can be handled by writing a regular expression
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000799which matches an entire header line, and has one group which matches the
800header name, and another group which matches the header's value.
801
802Groups are marked by the \character{(}, \character{)} metacharacters.
803\character{(} and \character{)} have much the same meaning as they do
804in mathematical expressions; they group together the expressions
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000805contained inside them, and you can repeat the contents of a
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000806group with a repeating qualifier, such as \regexp{*}, \regexp{+},
807\regexp{?}, or \regexp{\{\var{m},\var{n}\}}. For example,
808\regexp{(ab)*} will match zero or more repetitions of \samp{ab}.
809
810\begin{verbatim}
811>>> p = re.compile('(ab)*')
812>>> print p.match('ababababab').span()
813(0, 10)
814\end{verbatim}
815
816Groups indicated with \character{(}, \character{)} also capture the
817starting and ending index of the text that they match; this can be
818retrieved by passing an argument to \method{group()},
819\method{start()}, \method{end()}, and \method{span()}. Groups are
820numbered starting with 0. Group 0 is always present; it's the whole
821RE, so \class{MatchObject} methods all have group 0 as their default
822argument. Later we'll see how to express groups that don't capture
823the span of text that they match.
824
825\begin{verbatim}
826>>> p = re.compile('(a)b')
827>>> m = p.match('ab')
828>>> m.group()
829'ab'
830>>> m.group(0)
831'ab'
832\end{verbatim}
833
834Subgroups are numbered from left to right, from 1 upward. Groups can
835be nested; to determine the number, just count the opening parenthesis
836characters, going from left to right.
837
838\begin{verbatim}
839>>> p = re.compile('(a(b)c)d')
840>>> m = p.match('abcd')
841>>> m.group(0)
842'abcd'
843>>> m.group(1)
844'abc'
845>>> m.group(2)
846'b'
847\end{verbatim}
848
849\method{group()} can be passed multiple group numbers at a time, in
850which case it will return a tuple containing the corresponding values
851for those groups.
852
853\begin{verbatim}
854>>> m.group(2,1,2)
855('b', 'abc', 'b')
856\end{verbatim}
857
858The \method{groups()} method returns a tuple containing the strings
859for all the subgroups, from 1 up to however many there are.
860
861\begin{verbatim}
862>>> m.groups()
863('abc', 'b')
864\end{verbatim}
865
866Backreferences in a pattern allow you to specify that the contents of
867an earlier capturing group must also be found at the current location
868in the string. For example, \regexp{\e 1} will succeed if the exact
869contents of group 1 can be found at the current position, and fails
870otherwise. Remember that Python's string literals also use a
871backslash followed by numbers to allow including arbitrary characters
872in a string, so be sure to use a raw string when incorporating
873backreferences in a RE.
874
875For example, the following RE detects doubled words in a string.
876
877\begin{verbatim}
878>>> p = re.compile(r'(\b\w+)\s+\1')
879>>> p.search('Paris in the the spring').group()
880'the the'
881\end{verbatim}
882
883Backreferences like this aren't often useful for just searching
884through a string --- there are few text formats which repeat data in
885this way --- but you'll soon find out that they're \emph{very} useful
886when performing string substitutions.
887
888\subsection{Non-capturing and Named Groups}
889
890Elaborate REs may use many groups, both to capture substrings of
891interest, and to group and structure the RE itself. In complex REs,
892it becomes difficult to keep track of the group numbers. There are
893two features which help with this problem. Both of them use a common
894syntax for regular expression extensions, so we'll look at that first.
895
896Perl 5 added several additional features to standard regular
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000897expressions, and the Python \module{re} module supports most of them.
898It would have been difficult to choose new
899single-keystroke metacharacters or new special sequences beginning
900with \samp{\e} to represent the new features without making Perl's
901regular expressions confusingly different from standard REs. If you
902chose \samp{\&} as a new metacharacter, for example, old expressions
903would be assuming that
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000904\samp{\&} was a regular character and wouldn't have escaped it by
905writing \regexp{\e \&} or \regexp{[\&]}.
906
907The solution chosen by the Perl developers was to use \regexp{(?...)}
908as the extension syntax. \samp{?} immediately after a parenthesis was
909a syntax error because the \samp{?} would have nothing to repeat, so
910this didn't introduce any compatibility problems. The characters
911immediately after the \samp{?} indicate what extension is being used,
912so \regexp{(?=foo)} is one thing (a positive lookahead assertion) and
913\regexp{(?:foo)} is something else (a non-capturing group containing
914the subexpression \regexp{foo}).
915
916Python adds an extension syntax to Perl's extension syntax. If the
917first character after the question mark is a \samp{P}, you know that
918it's an extension that's specific to Python. Currently there are two
919such extensions: \regexp{(?P<\var{name}>...)} defines a named group,
920and \regexp{(?P=\var{name})} is a backreference to a named group. If
921future versions of Perl 5 add similar features using a different
922syntax, the \module{re} module will be changed to support the new
923syntax, while preserving the Python-specific syntax for
924compatibility's sake.
925
926Now that we've looked at the general extension syntax, we can return
927to the features that simplify working with groups in complex REs.
928Since groups are numbered from left to right and a complex expression
929may use many groups, it can become difficult to keep track of the
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000930correct numbering. Modifying such a complex RE is annoying, too:
931insert a new group near the beginning and you change the numbers of
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000932everything that follows it.
933
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000934Sometimes you'll want to use a group to collect a part of a regular
935expression, but aren't interested in retrieving the group's contents.
936You can make this fact explicit by using a non-capturing group:
937\regexp{(?:...)}, where you can replace the \regexp{...}
938with any other regular expression.
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000939
940\begin{verbatim}
941>>> m = re.match("([abc])+", "abc")
942>>> m.groups()
943('c',)
944>>> m = re.match("(?:[abc])+", "abc")
945>>> m.groups()
946()
947\end{verbatim}
948
949Except for the fact that you can't retrieve the contents of what the
950group matched, a non-capturing group behaves exactly the same as a
951capturing group; you can put anything inside it, repeat it with a
952repetition metacharacter such as \samp{*}, and nest it within other
953groups (capturing or non-capturing). \regexp{(?:...)} is particularly
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000954useful when modifying an existing pattern, since you can add new groups
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000955without changing how all the other groups are numbered. It should be
956mentioned that there's no performance difference in searching between
957capturing and non-capturing groups; neither form is any faster than
958the other.
959
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000960A more significant feature is named groups: instead of
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000961referring to them by numbers, groups can be referenced by a name.
962
963The syntax for a named group is one of the Python-specific extensions:
964\regexp{(?P<\var{name}>...)}. \var{name} is, obviously, the name of
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000965the group. Named groups also behave exactly like capturing groups,
966and additionally associate a name with a group. The
967\class{MatchObject} methods that deal with capturing groups all accept
968either integers that refer to the group by number or strings that
969contain the desired group's name. Named groups are still given
970numbers, so you can retrieve information about a group in two ways:
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000971
972\begin{verbatim}
973>>> p = re.compile(r'(?P<word>\b\w+\b)')
974>>> m = p.search( '(((( Lots of punctuation )))' )
975>>> m.group('word')
976'Lots'
977>>> m.group(1)
978'Lots'
979\end{verbatim}
980
981Named groups are handy because they let you use easily-remembered
982names, instead of having to remember numbers. Here's an example RE
983from the \module{imaplib} module:
984
985\begin{verbatim}
986InternalDate = re.compile(r'INTERNALDATE "'
987 r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-'
988 r'(?P<year>[0-9][0-9][0-9][0-9])'
989 r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
990 r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
991 r'"')
992\end{verbatim}
993
994It's obviously much easier to retrieve \code{m.group('zonem')},
995instead of having to remember to retrieve group 9.
996
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000997The syntax for backreferences in an expression such as
998\regexp{(...)\e 1} refers to the number of the group. There's
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000999naturally a variant that uses the group name instead of the number.
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001000This is another Python extension: \regexp{(?P=\var{name})} indicates
1001that the contents of the group called \var{name} should again be matched
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +00001002at the current point. The regular expression for finding doubled
1003words, \regexp{(\e b\e w+)\e s+\e 1} can also be written as
1004\regexp{(?P<word>\e b\e w+)\e s+(?P=word)}:
1005
1006\begin{verbatim}
1007>>> p = re.compile(r'(?P<word>\b\w+)\s+(?P=word)')
1008>>> p.search('Paris in the the spring').group()
1009'the the'
1010\end{verbatim}
1011
1012\subsection{Lookahead Assertions}
1013
1014Another zero-width assertion is the lookahead assertion. Lookahead
1015assertions are available in both positive and negative form, and
1016look like this:
1017
1018\begin{itemize}
1019\item[\regexp{(?=...)}] Positive lookahead assertion. This succeeds
1020if the contained regular expression, represented here by \code{...},
1021successfully matches at the current location, and fails otherwise.
1022But, once the contained expression has been tried, the matching engine
1023doesn't advance at all; the rest of the pattern is tried right where
1024the assertion started.
1025
1026\item[\regexp{(?!...)}] Negative lookahead assertion. This is the
1027opposite of the positive assertion; it succeeds if the contained expression
1028\emph{doesn't} match at the current position in the string.
1029\end{itemize}
1030
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001031To make this concrete, let's look at a case where a lookahead is
1032useful. Consider a simple pattern to match a filename and split it
1033apart into a base name and an extension, separated by a \samp{.}. For
1034example, in \samp{news.rc}, \samp{news} is the base name, and
1035\samp{rc} is the filename's extension.
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +00001036
1037The pattern to match this is quite simple:
1038
1039\regexp{.*[.].*\$}
1040
1041Notice that the \samp{.} needs to be treated specially because it's a
1042metacharacter; I've put it inside a character class. Also notice the
1043trailing \regexp{\$}; this is added to ensure that all the rest of the
1044string must be included in the extension. This regular expression
1045matches \samp{foo.bar} and \samp{autoexec.bat} and \samp{sendmail.cf} and
1046\samp{printers.conf}.
1047
1048Now, consider complicating the problem a bit; what if you want to
1049match filenames where the extension is not \samp{bat}?
1050Some incorrect attempts:
1051
1052\verb|.*[.][^b].*$|
1053% $
1054
1055The first attempt above tries to exclude \samp{bat} by requiring that
1056the first character of the extension is not a \samp{b}. This is
1057wrong, because the pattern also doesn't match \samp{foo.bar}.
1058
1059% Messes up the HTML without the curly braces around \^
1060\regexp{.*[.]([{\^}b]..|.[{\^}a].|..[{\^}t])\$}
1061
1062The expression gets messier when you try to patch up the first
1063solution by requiring one of the following cases to match: the first
1064character of the extension isn't \samp{b}; the second character isn't
1065\samp{a}; or the third character isn't \samp{t}. This accepts
1066\samp{foo.bar} and rejects \samp{autoexec.bat}, but it requires a
1067three-letter extension and won't accept a filename with a two-letter
1068extension such as \samp{sendmail.cf}. We'll complicate the pattern
1069again in an effort to fix it.
1070
1071\regexp{.*[.]([{\^}b].?.?|.[{\^}a]?.?|..?[{\^}t]?)\$}
1072
1073In the third attempt, the second and third letters are all made
1074optional in order to allow matching extensions shorter than three
1075characters, such as \samp{sendmail.cf}.
1076
1077The pattern's getting really complicated now, which makes it hard to
1078read and understand. Worse, if the problem changes and you want to
1079exclude both \samp{bat} and \samp{exe} as extensions, the pattern
1080would get even more complicated and confusing.
1081
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001082A negative lookahead cuts through all this confusion:
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +00001083
1084\regexp{.*[.](?!bat\$).*\$}
1085% $
1086
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001087The negative lookahead means: if the expression \regexp{bat} doesn't match at
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +00001088this point, try the rest of the pattern; if \regexp{bat\$} does match,
1089the whole pattern will fail. The trailing \regexp{\$} is required to
1090ensure that something like \samp{sample.batch}, where the extension
1091only starts with \samp{bat}, will be allowed.
1092
1093Excluding another filename extension is now easy; simply add it as an
1094alternative inside the assertion. The following pattern excludes
1095filenames that end in either \samp{bat} or \samp{exe}:
1096
1097\regexp{.*[.](?!bat\$|exe\$).*\$}
1098% $
1099
1100
1101\section{Modifying Strings}
1102
1103Up to this point, we've simply performed searches against a static
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001104string. Regular expressions are also commonly used to modify strings
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +00001105in various ways, using the following \class{RegexObject} methods:
1106
1107\begin{tableii}{c|l}{code}{Method/Attribute}{Purpose}
1108 \lineii{split()}{Split the string into a list, splitting it wherever the RE matches}
1109 \lineii{sub()}{Find all substrings where the RE matches, and replace them with a different string}
1110 \lineii{subn()}{Does the same thing as \method{sub()},
1111 but returns the new string and the number of replacements}
1112\end{tableii}
1113
1114
1115\subsection{Splitting Strings}
1116
1117The \method{split()} method of a \class{RegexObject} splits a string
1118apart wherever the RE matches, returning a list of the pieces.
1119It's similar to the \method{split()} method of strings but
1120provides much more
1121generality in the delimiters that you can split by;
1122\method{split()} only supports splitting by whitespace or by
1123a fixed string. As you'd expect, there's a module-level
1124\function{re.split()} function, too.
1125
1126\begin{methoddesc}{split}{string \optional{, maxsplit\code{ = 0}}}
1127 Split \var{string} by the matches of the regular expression. If
1128 capturing parentheses are used in the RE, then their contents will
1129 also be returned as part of the resulting list. If \var{maxsplit}
1130 is nonzero, at most \var{maxsplit} splits are performed.
1131\end{methoddesc}
1132
1133You can limit the number of splits made, by passing a value for
1134\var{maxsplit}. When \var{maxsplit} is nonzero, at most
1135\var{maxsplit} splits will be made, and the remainder of the string is
1136returned as the final element of the list. In the following example,
1137the delimiter is any sequence of non-alphanumeric characters.
1138
1139\begin{verbatim}
1140>>> p = re.compile(r'\W+')
1141>>> p.split('This is a test, short and sweet, of split().')
1142['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '']
1143>>> p.split('This is a test, short and sweet, of split().', 3)
1144['This', 'is', 'a', 'test, short and sweet, of split().']
1145\end{verbatim}
1146
1147Sometimes you're not only interested in what the text between
1148delimiters is, but also need to know what the delimiter was. If
1149capturing parentheses are used in the RE, then their values are also
1150returned as part of the list. Compare the following calls:
1151
1152\begin{verbatim}
1153>>> p = re.compile(r'\W+')
1154>>> p2 = re.compile(r'(\W+)')
1155>>> p.split('This... is a test.')
1156['This', 'is', 'a', 'test', '']
1157>>> p2.split('This... is a test.')
1158['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']
1159\end{verbatim}
1160
1161The module-level function \function{re.split()} adds the RE to be
1162used as the first argument, but is otherwise the same.
1163
1164\begin{verbatim}
1165>>> re.split('[\W]+', 'Words, words, words.')
1166['Words', 'words', 'words', '']
1167>>> re.split('([\W]+)', 'Words, words, words.')
1168['Words', ', ', 'words', ', ', 'words', '.', '']
1169>>> re.split('[\W]+', 'Words, words, words.', 1)
1170['Words', 'words, words.']
1171\end{verbatim}
1172
1173\subsection{Search and Replace}
1174
1175Another common task is to find all the matches for a pattern, and
1176replace them with a different string. The \method{sub()} method takes
1177a replacement value, which can be either a string or a function, and
1178the string to be processed.
1179
1180\begin{methoddesc}{sub}{replacement, string\optional{, count\code{ = 0}}}
1181Returns the string obtained by replacing the leftmost non-overlapping
1182occurrences of the RE in \var{string} by the replacement
1183\var{replacement}. If the pattern isn't found, \var{string} is returned
1184unchanged.
1185
1186The optional argument \var{count} is the maximum number of pattern
1187occurrences to be replaced; \var{count} must be a non-negative
1188integer. The default value of 0 means to replace all occurrences.
1189\end{methoddesc}
1190
1191Here's a simple example of using the \method{sub()} method. It
1192replaces colour names with the word \samp{colour}:
1193
1194\begin{verbatim}
1195>>> p = re.compile( '(blue|white|red)')
1196>>> p.sub( 'colour', 'blue socks and red shoes')
1197'colour socks and colour shoes'
1198>>> p.sub( 'colour', 'blue socks and red shoes', count=1)
1199'colour socks and red shoes'
1200\end{verbatim}
1201
1202The \method{subn()} method does the same work, but returns a 2-tuple
1203containing the new string value and the number of replacements
1204that were performed:
1205
1206\begin{verbatim}
1207>>> p = re.compile( '(blue|white|red)')
1208>>> p.subn( 'colour', 'blue socks and red shoes')
1209('colour socks and colour shoes', 2)
1210>>> p.subn( 'colour', 'no colours at all')
1211('no colours at all', 0)
1212\end{verbatim}
1213
1214Empty matches are replaced only when they're not
1215adjacent to a previous match.
1216
1217\begin{verbatim}
1218>>> p = re.compile('x*')
1219>>> p.sub('-', 'abxd')
1220'-a-b-d-'
1221\end{verbatim}
1222
1223If \var{replacement} is a string, any backslash escapes in it are
1224processed. That is, \samp{\e n} is converted to a single newline
1225character, \samp{\e r} is converted to a carriage return, and so forth.
1226Unknown escapes such as \samp{\e j} are left alone. Backreferences,
1227such as \samp{\e 6}, are replaced with the substring matched by the
1228corresponding group in the RE. This lets you incorporate
1229portions of the original text in the resulting
1230replacement string.
1231
1232This example matches the word \samp{section} followed by a string
1233enclosed in \samp{\{}, \samp{\}}, and changes \samp{section} to
1234\samp{subsection}:
1235
1236\begin{verbatim}
1237>>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE)
1238>>> p.sub(r'subsection{\1}','section{First} section{second}')
1239'subsection{First} subsection{second}'
1240\end{verbatim}
1241
1242There's also a syntax for referring to named groups as defined by the
1243\regexp{(?P<name>...)} syntax. \samp{\e g<name>} will use the
1244substring matched by the group named \samp{name}, and
1245\samp{\e g<\var{number}>}
1246uses the corresponding group number.
1247\samp{\e g<2>} is therefore equivalent to \samp{\e 2},
1248but isn't ambiguous in a
1249replacement string such as \samp{\e g<2>0}. (\samp{\e 20} would be
1250interpreted as a reference to group 20, not a reference to group 2
1251followed by the literal character \character{0}.) The following
1252substitutions are all equivalent, but use all three variations of the
1253replacement string.
1254
1255\begin{verbatim}
1256>>> p = re.compile('section{ (?P<name> [^}]* ) }', re.VERBOSE)
1257>>> p.sub(r'subsection{\1}','section{First}')
1258'subsection{First}'
1259>>> p.sub(r'subsection{\g<1>}','section{First}')
1260'subsection{First}'
1261>>> p.sub(r'subsection{\g<name>}','section{First}')
1262'subsection{First}'
1263\end{verbatim}
1264
1265\var{replacement} can also be a function, which gives you even more
1266control. If \var{replacement} is a function, the function is
1267called for every non-overlapping occurrence of \var{pattern}. On each
1268call, the function is
1269passed a \class{MatchObject} argument for the match
1270and can use this information to compute the desired replacement string and return it.
1271
1272In the following example, the replacement function translates
1273decimals into hexadecimal:
1274
1275\begin{verbatim}
1276>>> def hexrepl( match ):
1277... "Return the hex string for a decimal number"
1278... value = int( match.group() )
1279... return hex(value)
1280...
1281>>> p = re.compile(r'\d+')
1282>>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
1283'Call 0xffd2 for printing, 0xc000 for user code.'
1284\end{verbatim}
1285
1286When using the module-level \function{re.sub()} function, the pattern
1287is passed as the first argument. The pattern may be a string or a
1288\class{RegexObject}; if you need to specify regular expression flags,
1289you must either use a \class{RegexObject} as the first parameter, or use
1290embedded modifiers in the pattern, e.g. \code{sub("(?i)b+", "x", "bbbb
1291BBBB")} returns \code{'x x'}.
1292
1293\section{Common Problems}
1294
1295Regular expressions are a powerful tool for some applications, but in
1296some ways their behaviour isn't intuitive and at times they don't
1297behave the way you may expect them to. This section will point out
1298some of the most common pitfalls.
1299
1300\subsection{Use String Methods}
1301
1302Sometimes using the \module{re} module is a mistake. If you're
1303matching a fixed string, or a single character class, and you're not
1304using any \module{re} features such as the \constant{IGNORECASE} flag,
1305then the full power of regular expressions may not be required.
1306Strings have several methods for performing operations with fixed
1307strings and they're usually much faster, because the implementation is
1308a single small C loop that's been optimized for the purpose, instead
1309of the large, more generalized regular expression engine.
1310
1311One example might be replacing a single fixed string with another
1312one; for example, you might replace \samp{word}
1313with \samp{deed}. \code{re.sub()} seems like the function to use for
1314this, but consider the \method{replace()} method. Note that
1315\function{replace()} will also replace \samp{word} inside
1316words, turning \samp{swordfish} into \samp{sdeedfish}, but the
1317na{\"\i}ve RE \regexp{word} would have done that, too. (To avoid performing
1318the substitution on parts of words, the pattern would have to be
1319\regexp{\e bword\e b}, in order to require that \samp{word} have a
1320word boundary on either side. This takes the job beyond
1321\method{replace}'s abilities.)
1322
1323Another common task is deleting every occurrence of a single character
1324from a string or replacing it with another single character. You
1325might do this with something like \code{re.sub('\e n', ' ', S)}, but
1326\method{translate()} is capable of doing both tasks
Andrew M. Kuchlingc28dd1f2005-08-31 17:49:38 +00001327and will be faster than any regular expression operation can be.
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +00001328
1329In short, before turning to the \module{re} module, consider whether
1330your problem can be solved with a faster and simpler string method.
1331
1332\subsection{match() versus search()}
1333
1334The \function{match()} function only checks if the RE matches at
1335the beginning of the string while \function{search()} will scan
1336forward through the string for a match.
1337It's important to keep this distinction in mind. Remember,
1338\function{match()} will only report a successful match which
1339will start at 0; if the match wouldn't start at zero,
1340\function{match()} will \emph{not} report it.
1341
1342\begin{verbatim}
1343>>> print re.match('super', 'superstition').span()
1344(0, 5)
1345>>> print re.match('super', 'insuperable')
1346None
1347\end{verbatim}
1348
1349On the other hand, \function{search()} will scan forward through the
1350string, reporting the first match it finds.
1351
1352\begin{verbatim}
1353>>> print re.search('super', 'superstition').span()
1354(0, 5)
1355>>> print re.search('super', 'insuperable').span()
1356(2, 7)
1357\end{verbatim}
1358
1359Sometimes you'll be tempted to keep using \function{re.match()}, and
1360just add \regexp{.*} to the front of your RE. Resist this temptation
1361and use \function{re.search()} instead. The regular expression
1362compiler does some analysis of REs in order to speed up the process of
1363looking for a match. One such analysis figures out what the first
1364character of a match must be; for example, a pattern starting with
1365\regexp{Crow} must match starting with a \character{C}. The analysis
1366lets the engine quickly scan through the string looking for the
1367starting character, only trying the full match if a \character{C} is found.
1368
1369Adding \regexp{.*} defeats this optimization, requiring scanning to
1370the end of the string and then backtracking to find a match for the
1371rest of the RE. Use \function{re.search()} instead.
1372
1373\subsection{Greedy versus Non-Greedy}
1374
1375When repeating a regular expression, as in \regexp{a*}, the resulting
1376action is to consume as much of the pattern as possible. This
1377fact often bites you when you're trying to match a pair of
1378balanced delimiters, such as the angle brackets surrounding an HTML
1379tag. The na{\"\i}ve pattern for matching a single HTML tag doesn't
1380work because of the greedy nature of \regexp{.*}.
1381
1382\begin{verbatim}
1383>>> s = '<html><head><title>Title</title>'
1384>>> len(s)
138532
1386>>> print re.match('<.*>', s).span()
1387(0, 32)
1388>>> print re.match('<.*>', s).group()
1389<html><head><title>Title</title>
1390\end{verbatim}
1391
1392The RE matches the \character{<} in \samp{<html>}, and the
1393\regexp{.*} consumes the rest of the string. There's still more left
1394in the RE, though, and the \regexp{>} can't match at the end of
1395the string, so the regular expression engine has to backtrack
1396character by character until it finds a match for the \regexp{>}.
1397The final match extends from the \character{<} in \samp{<html>}
1398to the \character{>} in \samp{</title>}, which isn't what you want.
1399
1400In this case, the solution is to use the non-greedy qualifiers
1401\regexp{*?}, \regexp{+?}, \regexp{??}, or
1402\regexp{\{\var{m},\var{n}\}?}, which match as \emph{little} text as
1403possible. In the above example, the \character{>} is tried
1404immediately after the first \character{<} matches, and when it fails,
1405the engine advances a character at a time, retrying the \character{>}
1406at every step. This produces just the right result:
1407
1408\begin{verbatim}
1409>>> print re.match('<.*?>', s).group()
1410<html>
1411\end{verbatim}
1412
1413(Note that parsing HTML or XML with regular expressions is painful.
1414Quick-and-dirty patterns will handle common cases, but HTML and XML
1415have special cases that will break the obvious regular expression; by
1416the time you've written a regular expression that handles all of the
1417possible cases, the patterns will be \emph{very} complicated. Use an
1418HTML or XML parser module for such tasks.)
1419
1420\subsection{Not Using re.VERBOSE}
1421
1422By now you've probably noticed that regular expressions are a very
1423compact notation, but they're not terribly readable. REs of
1424moderate complexity can become lengthy collections of backslashes,
1425parentheses, and metacharacters, making them difficult to read and
1426understand.
1427
1428For such REs, specifying the \code{re.VERBOSE} flag when
1429compiling the regular expression can be helpful, because it allows
1430you to format the regular expression more clearly.
1431
1432The \code{re.VERBOSE} flag has several effects. Whitespace in the
1433regular expression that \emph{isn't} inside a character class is
1434ignored. This means that an expression such as \regexp{dog | cat} is
1435equivalent to the less readable \regexp{dog|cat}, but \regexp{[a b]}
1436will still match the characters \character{a}, \character{b}, or a
1437space. In addition, you can also put comments inside a RE; comments
1438extend from a \samp{\#} character to the next newline. When used with
1439triple-quoted strings, this enables REs to be formatted more neatly:
1440
1441\begin{verbatim}
1442pat = re.compile(r"""
1443 \s* # Skip leading whitespace
1444 (?P<header>[^:]+) # Header name
1445 \s* : # Whitespace, and a colon
1446 (?P<value>.*?) # The header's value -- *? used to
1447 # lose the following trailing whitespace
1448 \s*$ # Trailing whitespace to end-of-line
1449""", re.VERBOSE)
1450\end{verbatim}
1451% $
1452
1453This is far more readable than:
1454
1455\begin{verbatim}
1456pat = re.compile(r"\s*(?P<header>[^:]+)\s*:(?P<value>.*?)\s*$")
1457\end{verbatim}
1458% $
1459
1460\section{Feedback}
1461
1462Regular expressions are a complicated topic. Did this document help
1463you understand them? Were there parts that were unclear, or Problems
1464you encountered that weren't covered here? If so, please send
1465suggestions for improvements to the author.
1466
1467The most complete book on regular expressions is almost certainly
1468Jeffrey Friedl's \citetitle{Mastering Regular Expressions}, published
1469by O'Reilly. Unfortunately, it exclusively concentrates on Perl and
1470Java's flavours of regular expressions, and doesn't contain any Python
1471material at all, so it won't be useful as a reference for programming
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001472in Python. (The first edition covered Python's now-removed
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +00001473\module{regex} module, which won't help you much.) Consider checking
1474it out from your library.
1475
1476\end{document}
1477