-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregex.html
More file actions
1551 lines (1522 loc) · 149 KB
/
regex.html
File metadata and controls
1551 lines (1522 loc) · 149 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_TW">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>如何使用正規表達式 — Python 3.7.0 說明文件</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/translations.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="在 Python 3.7.0 說明文件 中搜尋"
href="../_static/opensearch.xml"/>
<link rel="author" title="關於這些文件" href="../about.html" />
<link rel="index" title="索引" href="../genindex.html" />
<link rel="search" title="搜尋" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="Socket Programming HOWTO" href="sockets.html" />
<link rel="prev" title="Logging Cookbook" href="logging-cookbook.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/howto/regex.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<h3>瀏覽</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">索引</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python 模組索引"
>模組</a> |</li>
<li class="right" >
<a href="sockets.html" title="Socket Programming HOWTO"
accesskey="N">下一頁</a> |</li>
<li class="right" >
<a href="logging-cookbook.html" title="Logging Cookbook"
accesskey="P">上一頁</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> »</li>
<li>
<span class="language_switcher_placeholder">zh_TW</span>
<span class="version_switcher_placeholder">3.7.0</span>
<a href="../index.html">Documentation </a> »
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> »</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="regular-expression-howto">
<span id="regex-howto"></span><h1>如何使用正規表達式<a class="headerlink" href="#regular-expression-howto" title="本標題的永久連結">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">A.M. Kuchling <<a class="reference external" href="mailto:amk%40amk.ca">amk<span>@</span>amk<span>.</span>ca</a>></td>
</tr>
</tbody>
</table>
<div class="topic">
<p class="topic-title first">Abstract</p>
<p>此文件為如何在 Python 中使用 <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> 模組來撰寫正規表達式的入門指導。進階使用及參考文件請見函式庫參考一章。</p>
</div>
<div class="section" id="introduction">
<h2>簡介<a class="headerlink" href="#introduction" title="本標題的永久連結">¶</a></h2>
<p>正規表示式 (也稱為 REs、regexes 或 regex patterns) 是一個輕量且高專業化的程式語言。在 Python 中可透過內建的 <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> 模組直接使用。你可以使用此輕量化的語言針對想要匹配的一組字串撰寫規則,這組字串可能包含了英語句子、e-mail 地址、TeX 命令或任何東西。你可以檢查如「這組字串是否匹配這個規則?」或「這組字串中是否有任一處匹配這個規則?」。除此之外,你也可以使用 REs 來修改或是切割字串。</p>
<p>Regular expression patterns are compiled into a series of bytecodes which are
then executed by a matching engine written in C. For advanced use, it may be
necessary to pay careful attention to how the engine will execute a given RE,
and write the RE in a certain way in order to produce bytecode that runs faster.
Optimization isn’t covered in this document, because it requires that you have a
good understanding of the matching engine’s internals.</p>
<p>The regular expression language is relatively small and restricted, so not all
possible string processing tasks can be done using regular expressions. There
are also tasks that <em>can</em> be done with regular expressions, but the expressions
turn out to be very complicated. In these cases, you may be better off writing
Python code to do the processing; while Python code will be slower than an
elaborate regular expression, it will also probably be more understandable.</p>
</div>
<div class="section" id="simple-patterns">
<h2>Simple Patterns<a class="headerlink" href="#simple-patterns" title="本標題的永久連結">¶</a></h2>
<p>We’ll start by learning about the simplest possible regular expressions. Since
regular expressions are used to operate on strings, we’ll begin with the most
common task: matching characters.</p>
<p>For a detailed explanation of the computer science underlying regular
expressions (deterministic and non-deterministic finite automata), you can refer
to almost any textbook on writing compilers.</p>
<div class="section" id="matching-characters">
<h3>Matching Characters<a class="headerlink" href="#matching-characters" title="本標題的永久連結">¶</a></h3>
<p>Most letters and characters will simply match themselves. For example, the
regular expression <code class="docutils literal notranslate"><span class="pre">test</span></code> will match the string <code class="docutils literal notranslate"><span class="pre">test</span></code> exactly. (You can
enable a case-insensitive mode that would let this RE match <code class="docutils literal notranslate"><span class="pre">Test</span></code> or <code class="docutils literal notranslate"><span class="pre">TEST</span></code>
as well; more about this later.)</p>
<p>There are exceptions to this rule; some characters are special
<em class="dfn">metacharacters</em>, and don’t match themselves. Instead, they signal that
some out-of-the-ordinary thing should be matched, or they affect other portions
of the RE by repeating them or changing their meaning. Much of this document is
devoted to discussing various metacharacters and what they do.</p>
<p>Here’s a complete list of the metacharacters; their meanings will be discussed
in the rest of this HOWTO.</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>. ^ $ * + ? { } [ ] \ | ( )
</pre></div>
</div>
<p>The first metacharacters we’ll look at are <code class="docutils literal notranslate"><span class="pre">[</span></code> and <code class="docutils literal notranslate"><span class="pre">]</span></code>. They’re used for
specifying a character class, which is a set of characters that you wish to
match. Characters can be listed individually, or a range of characters can be
indicated by giving two characters and separating them by a <code class="docutils literal notranslate"><span class="pre">'-'</span></code>. For
example, <code class="docutils literal notranslate"><span class="pre">[abc]</span></code> will match any of the characters <code class="docutils literal notranslate"><span class="pre">a</span></code>, <code class="docutils literal notranslate"><span class="pre">b</span></code>, or <code class="docutils literal notranslate"><span class="pre">c</span></code>; this
is the same as <code class="docutils literal notranslate"><span class="pre">[a-c]</span></code>, which uses a range to express the same set of
characters. If you wanted to match only lowercase letters, your RE would be
<code class="docutils literal notranslate"><span class="pre">[a-z]</span></code>.</p>
<p>Metacharacters are not active inside classes. For example, <code class="docutils literal notranslate"><span class="pre">[akm$]</span></code> will
match any of the characters <code class="docutils literal notranslate"><span class="pre">'a'</span></code>, <code class="docutils literal notranslate"><span class="pre">'k'</span></code>, <code class="docutils literal notranslate"><span class="pre">'m'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'$'</span></code>; <code class="docutils literal notranslate"><span class="pre">'$'</span></code> is
usually a metacharacter, but inside a character class it’s stripped of its
special nature.</p>
<p>You can match the characters not listed within the class by <em class="dfn">complementing</em>
the set. This is indicated by including a <code class="docutils literal notranslate"><span class="pre">'^'</span></code> as the first character of the
class; <code class="docutils literal notranslate"><span class="pre">'^'</span></code> outside a character class will simply match the <code class="docutils literal notranslate"><span class="pre">'^'</span></code>
character. For example, <code class="docutils literal notranslate"><span class="pre">[^5]</span></code> will match any character except <code class="docutils literal notranslate"><span class="pre">'5'</span></code>.</p>
<p>Perhaps the most important metacharacter is the backslash, <code class="docutils literal notranslate"><span class="pre">\</span></code>. As in Python
string literals, the backslash can be followed by various characters to signal
various special sequences. It’s also used to escape all the metacharacters so
you can still match them in patterns; for example, if you need to match a <code class="docutils literal notranslate"><span class="pre">[</span></code>
or <code class="docutils literal notranslate"><span class="pre">\</span></code>, you can precede them with a backslash to remove their special
meaning: <code class="docutils literal notranslate"><span class="pre">\[</span></code> or <code class="docutils literal notranslate"><span class="pre">\\</span></code>.</p>
<p>Some of the special sequences beginning with <code class="docutils literal notranslate"><span class="pre">'\'</span></code> represent
predefined sets of characters that are often useful, such as the set
of digits, the set of letters, or the set of anything that isn’t
whitespace.</p>
<p>Let’s take an example: <code class="docutils literal notranslate"><span class="pre">\w</span></code> matches any alphanumeric character. If
the regex pattern is expressed in bytes, this is equivalent to the
class <code class="docutils literal notranslate"><span class="pre">[a-zA-Z0-9_]</span></code>. If the regex pattern is a string, <code class="docutils literal notranslate"><span class="pre">\w</span></code> will
match all the characters marked as letters in the Unicode database
provided by the <a class="reference internal" href="../library/unicodedata.html#module-unicodedata" title="unicodedata: Access the Unicode Database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unicodedata</span></code></a> module. You can use the more
restricted definition of <code class="docutils literal notranslate"><span class="pre">\w</span></code> in a string pattern by supplying the
<a class="reference internal" href="../library/re.html#re.ASCII" title="re.ASCII"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.ASCII</span></code></a> flag when compiling the regular expression.</p>
<p>The following list of special sequences isn’t complete. For a complete
list of sequences and expanded class definitions for Unicode string
patterns, see the last part of <a class="reference internal" href="../library/re.html#re-syntax"><span class="std std-ref">Regular Expression Syntax</span></a> in the Standard Library reference. In general, the
Unicode versions match any character that’s in the appropriate
category in the Unicode database.</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">\d</span></code></dt>
<dd>Matches any decimal digit; this is equivalent to the class <code class="docutils literal notranslate"><span class="pre">[0-9]</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\D</span></code></dt>
<dd>Matches any non-digit character; this is equivalent to the class <code class="docutils literal notranslate"><span class="pre">[^0-9]</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\s</span></code></dt>
<dd>Matches any whitespace character; this is equivalent to the class <code class="docutils literal notranslate"><span class="pre">[</span>
<span class="pre">\t\n\r\f\v]</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\S</span></code></dt>
<dd>Matches any non-whitespace character; this is equivalent to the class <code class="docutils literal notranslate"><span class="pre">[^</span>
<span class="pre">\t\n\r\f\v]</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\w</span></code></dt>
<dd>Matches any alphanumeric character; this is equivalent to the class
<code class="docutils literal notranslate"><span class="pre">[a-zA-Z0-9_]</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\W</span></code></dt>
<dd>Matches any non-alphanumeric character; this is equivalent to the class
<code class="docutils literal notranslate"><span class="pre">[^a-zA-Z0-9_]</span></code>.</dd>
</dl>
<p>These sequences can be included inside a character class. For example,
<code class="docutils literal notranslate"><span class="pre">[\s,.]</span></code> is a character class that will match any whitespace character, or
<code class="docutils literal notranslate"><span class="pre">','</span></code> or <code class="docutils literal notranslate"><span class="pre">'.'</span></code>.</p>
<p>The final metacharacter in this section is <code class="docutils literal notranslate"><span class="pre">.</span></code>. It matches anything except a
newline character, and there’s an alternate mode (<a class="reference internal" href="../library/re.html#re.DOTALL" title="re.DOTALL"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.DOTALL</span></code></a>) where it will
match even a newline. <code class="docutils literal notranslate"><span class="pre">.</span></code> is often used where you want to match 「any
character」.</p>
</div>
<div class="section" id="repeating-things">
<h3>Repeating Things<a class="headerlink" href="#repeating-things" title="本標題的永久連結">¶</a></h3>
<p>Being able to match varying sets of characters is the first thing regular
expressions can do that isn’t already possible with the methods available on
strings. However, if that was the only additional capability of regexes, they
wouldn’t be much of an advance. Another capability is that you can specify that
portions of the RE must be repeated a certain number of times.</p>
<p>The first metacharacter for repeating things that we’ll look at is <code class="docutils literal notranslate"><span class="pre">*</span></code>. <code class="docutils literal notranslate"><span class="pre">*</span></code>
doesn’t match the literal character <code class="docutils literal notranslate"><span class="pre">'*'</span></code>; instead, it specifies that the
previous character can be matched zero or more times, instead of exactly once.</p>
<p>For example, <code class="docutils literal notranslate"><span class="pre">ca*t</span></code> will match <code class="docutils literal notranslate"><span class="pre">'ct'</span></code> (0 <code class="docutils literal notranslate"><span class="pre">'a'</span></code> characters), <code class="docutils literal notranslate"><span class="pre">'cat'</span></code> (1 <code class="docutils literal notranslate"><span class="pre">'a'</span></code>),
<code class="docutils literal notranslate"><span class="pre">'caaat'</span></code> (3 <code class="docutils literal notranslate"><span class="pre">'a'</span></code> characters), and so forth.</p>
<p>Repetitions such as <code class="docutils literal notranslate"><span class="pre">*</span></code> are <em class="dfn">greedy</em>; when repeating a RE, the matching
engine will try to repeat it as many times as possible. If later portions of the
pattern don’t match, the matching engine will then back up and try again with
fewer repetitions.</p>
<p>A step-by-step example will make this more obvious. Let’s consider the
expression <code class="docutils literal notranslate"><span class="pre">a[bcd]*b</span></code>. This matches the letter <code class="docutils literal notranslate"><span class="pre">'a'</span></code>, zero or more letters
from the class <code class="docutils literal notranslate"><span class="pre">[bcd]</span></code>, and finally ends with a <code class="docutils literal notranslate"><span class="pre">'b'</span></code>. Now imagine matching
this RE against the string <code class="docutils literal notranslate"><span class="pre">'abcbd'</span></code>.</p>
<table border="1" class="docutils">
<colgroup>
<col width="12%" />
<col width="22%" />
<col width="66%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Step</th>
<th class="head">Matched</th>
<th class="head">Explanation</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>1</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span></code></td>
<td>The <code class="docutils literal notranslate"><span class="pre">a</span></code> in the RE matches.</td>
</tr>
<tr class="row-odd"><td>2</td>
<td><code class="docutils literal notranslate"><span class="pre">abcbd</span></code></td>
<td>The engine matches <code class="docutils literal notranslate"><span class="pre">[bcd]*</span></code>,
going as far as it can, which
is to the end of the string.</td>
</tr>
<tr class="row-even"><td>3</td>
<td><em>Failure</em></td>
<td>The engine tries to match
<code class="docutils literal notranslate"><span class="pre">b</span></code>, but the current position
is at the end of the string, so
it fails.</td>
</tr>
<tr class="row-odd"><td>4</td>
<td><code class="docutils literal notranslate"><span class="pre">abcb</span></code></td>
<td>Back up, so that <code class="docutils literal notranslate"><span class="pre">[bcd]*</span></code>
matches one less character.</td>
</tr>
<tr class="row-even"><td>5</td>
<td><em>Failure</em></td>
<td>Try <code class="docutils literal notranslate"><span class="pre">b</span></code> again, but the
current position is at the last
character, which is a <code class="docutils literal notranslate"><span class="pre">'d'</span></code>.</td>
</tr>
<tr class="row-odd"><td>6</td>
<td><code class="docutils literal notranslate"><span class="pre">abc</span></code></td>
<td>Back up again, so that
<code class="docutils literal notranslate"><span class="pre">[bcd]*</span></code> is only matching
<code class="docutils literal notranslate"><span class="pre">bc</span></code>.</td>
</tr>
<tr class="row-even"><td>6</td>
<td><code class="docutils literal notranslate"><span class="pre">abcb</span></code></td>
<td>Try <code class="docutils literal notranslate"><span class="pre">b</span></code> again. This time
the character at the
current position is <code class="docutils literal notranslate"><span class="pre">'b'</span></code>, so
it succeeds.</td>
</tr>
</tbody>
</table>
<p>The end of the RE has now been reached, and it has matched <code class="docutils literal notranslate"><span class="pre">'abcb'</span></code>. This
demonstrates how the matching engine goes as far as it can at first, and if no
match is found it will then progressively back up and retry the rest of the RE
again and again. It will back up until it has tried zero matches for
<code class="docutils literal notranslate"><span class="pre">[bcd]*</span></code>, and if that subsequently fails, the engine will conclude that the
string doesn’t match the RE at all.</p>
<p>Another repeating metacharacter is <code class="docutils literal notranslate"><span class="pre">+</span></code>, which matches one or more times. Pay
careful attention to the difference between <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">+</span></code>; <code class="docutils literal notranslate"><span class="pre">*</span></code> matches
<em>zero</em> or more times, so whatever’s being repeated may not be present at all,
while <code class="docutils literal notranslate"><span class="pre">+</span></code> requires at least <em>one</em> occurrence. To use a similar example,
<code class="docutils literal notranslate"><span class="pre">ca+t</span></code> will match <code class="docutils literal notranslate"><span class="pre">'cat'</span></code> (1 <code class="docutils literal notranslate"><span class="pre">'a'</span></code>), <code class="docutils literal notranslate"><span class="pre">'caaat'</span></code> (3 <code class="docutils literal notranslate"><span class="pre">'a'</span></code>s), but won’t
match <code class="docutils literal notranslate"><span class="pre">'ct'</span></code>.</p>
<p>There are two more repeating qualifiers. The question mark character, <code class="docutils literal notranslate"><span class="pre">?</span></code>,
matches either once or zero times; you can think of it as marking something as
being optional. For example, <code class="docutils literal notranslate"><span class="pre">home-?brew</span></code> matches either <code class="docutils literal notranslate"><span class="pre">'homebrew'</span></code> or
<code class="docutils literal notranslate"><span class="pre">'home-brew'</span></code>.</p>
<p>The most complicated repeated qualifier is <code class="docutils literal notranslate"><span class="pre">{m,n}</span></code>, where <em>m</em> and <em>n</em> are
decimal integers. This qualifier means there must be at least <em>m</em> repetitions,
and at most <em>n</em>. For example, <code class="docutils literal notranslate"><span class="pre">a/{1,3}b</span></code> will match <code class="docutils literal notranslate"><span class="pre">'a/b'</span></code>, <code class="docutils literal notranslate"><span class="pre">'a//b'</span></code>, and
<code class="docutils literal notranslate"><span class="pre">'a///b'</span></code>. It won’t match <code class="docutils literal notranslate"><span class="pre">'ab'</span></code>, which has no slashes, or <code class="docutils literal notranslate"><span class="pre">'a////b'</span></code>, which
has four.</p>
<p>You can omit either <em>m</em> or <em>n</em>; in that case, a reasonable value is assumed for
the missing value. Omitting <em>m</em> is interpreted as a lower limit of 0, while
omitting <em>n</em> results in an upper bound of infinity.</p>
<p>Readers of a reductionist bent may notice that the three other qualifiers can
all be expressed using this notation. <code class="docutils literal notranslate"><span class="pre">{0,}</span></code> is the same as <code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">{1,}</span></code>
is equivalent to <code class="docutils literal notranslate"><span class="pre">+</span></code>, and <code class="docutils literal notranslate"><span class="pre">{0,1}</span></code> is the same as <code class="docutils literal notranslate"><span class="pre">?</span></code>. It’s better to use
<code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">+</span></code>, or <code class="docutils literal notranslate"><span class="pre">?</span></code> when you can, simply because they’re shorter and easier
to read.</p>
</div>
</div>
<div class="section" id="using-regular-expressions">
<h2>Using Regular Expressions<a class="headerlink" href="#using-regular-expressions" title="本標題的永久連結">¶</a></h2>
<p>Now that we’ve looked at some simple regular expressions, how do we actually use
them in Python? The <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module provides an interface to the regular
expression engine, allowing you to compile REs into objects and then perform
matches with them.</p>
<div class="section" id="compiling-regular-expressions">
<h3>Compiling Regular Expressions<a class="headerlink" href="#compiling-regular-expressions" title="本標題的永久連結">¶</a></h3>
<p>Regular expressions are compiled into pattern objects, which have
methods for various operations such as searching for pattern matches or
performing string substitutions.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">>>> </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">'ab*'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">p</span>
<span class="go">re.compile('ab*')</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/re.html#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> also accepts an optional <em>flags</em> argument, used to enable
various special features and syntax variations. We’ll go over the available
settings later, but for now a single example will do:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">'ab*'</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">IGNORECASE</span><span class="p">)</span>
</pre></div>
</div>
<p>The RE is passed to <a class="reference internal" href="../library/re.html#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> as a string. REs are handled as strings
because regular expressions aren’t part of the core Python language, and no
special syntax was created for expressing them. (There are applications that
don’t need REs at all, so there’s no need to bloat the language specification by
including them.) Instead, the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module is simply a C extension module
included with Python, just like the <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> or <a class="reference internal" href="../library/zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> modules.</p>
<p>Putting REs in strings keeps the Python language simpler, but has one
disadvantage which is the topic of the next section.</p>
</div>
<div class="section" id="the-backslash-plague">
<span id="id1"></span><h3>The Backslash Plague<a class="headerlink" href="#the-backslash-plague" title="本標題的永久連結">¶</a></h3>
<p>As stated earlier, regular expressions use the backslash character (<code class="docutils literal notranslate"><span class="pre">'\'</span></code>) to
indicate special forms or to allow special characters to be used without
invoking their special meaning. This conflicts with Python’s usage of the same
character for the same purpose in string literals.</p>
<p>Let’s say you want to write a RE that matches the string <code class="docutils literal notranslate"><span class="pre">\section</span></code>, which
might be found in a LaTeX file. To figure out what to write in the program
code, start with the desired string to be matched. Next, you must escape any
backslashes and other metacharacters by preceding them with a backslash,
resulting in the string <code class="docutils literal notranslate"><span class="pre">\\section</span></code>. The resulting string that must be passed
to <a class="reference internal" href="../library/re.html#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> must be <code class="docutils literal notranslate"><span class="pre">\\section</span></code>. However, to express this as a
Python string literal, both backslashes must be escaped <em>again</em>.</p>
<table border="1" class="docutils">
<colgroup>
<col width="31%" />
<col width="69%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Characters</th>
<th class="head">Stage</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">\section</span></code></td>
<td>Text string to be matched</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">\\section</span></code></td>
<td>Escaped backslash for <a class="reference internal" href="../library/re.html#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">"\\\\section"</span></code></td>
<td>Escaped backslashes for a string literal</td>
</tr>
</tbody>
</table>
<p>In short, to match a literal backslash, one has to write <code class="docutils literal notranslate"><span class="pre">'\\\\'</span></code> as the RE
string, because the regular expression must be <code class="docutils literal notranslate"><span class="pre">\\</span></code>, and each backslash must
be expressed as <code class="docutils literal notranslate"><span class="pre">\\</span></code> inside a regular Python string literal. In REs that
feature backslashes repeatedly, this leads to lots of repeated backslashes and
makes the resulting strings difficult to understand.</p>
<p>The solution is to use Python’s raw string notation for regular expressions;
backslashes are not handled in any special way in a string literal prefixed with
<code class="docutils literal notranslate"><span class="pre">'r'</span></code>, so <code class="docutils literal notranslate"><span class="pre">r"\n"</span></code> is a two-character string containing <code class="docutils literal notranslate"><span class="pre">'\'</span></code> and <code class="docutils literal notranslate"><span class="pre">'n'</span></code>,
while <code class="docutils literal notranslate"><span class="pre">"\n"</span></code> is a one-character string containing a newline. Regular
expressions will often be written in Python code using this raw string notation.</p>
<p>In addition, special escape sequences that are valid in regular expressions,
but not valid as Python string literals, now result in a
<a class="reference internal" href="../library/exceptions.html#DeprecationWarning" title="DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> and will eventually become a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>,
which means the sequences will be invalid if raw string notation or escaping
the backslashes isn’t used.</p>
<table border="1" class="docutils">
<colgroup>
<col width="51%" />
<col width="49%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Regular String</th>
<th class="head">Raw string</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">"ab*"</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">r"ab*"</span></code></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">"\\\\section"</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">r"\\section"</span></code></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">"\\w+\\s+\\1"</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">r"\w+\s+\1"</span></code></td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="performing-matches">
<h3>Performing Matches<a class="headerlink" href="#performing-matches" title="本標題的永久連結">¶</a></h3>
<p>Once you have an object representing a compiled regular expression, what do you
do with it? Pattern objects have several methods and attributes.
Only the most significant ones will be covered here; consult the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> docs
for a complete listing.</p>
<table border="1" class="docutils">
<colgroup>
<col width="28%" />
<col width="72%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Method/Attribute</th>
<th class="head">Purpose</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">match()</span></code></td>
<td>Determine if the RE matches at the beginning
of the string.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">search()</span></code></td>
<td>Scan through a string, looking for any
location where this RE matches.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">findall()</span></code></td>
<td>Find all substrings where the RE matches, and
returns them as a list.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">finditer()</span></code></td>
<td>Find all substrings where the RE matches, and
returns them as an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>.</td>
</tr>
</tbody>
</table>
<p><a class="reference internal" href="../library/re.html#re.Pattern.match" title="re.Pattern.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a> and <a class="reference internal" href="../library/re.html#re.Pattern.search" title="re.Pattern.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a> return <code class="docutils literal notranslate"><span class="pre">None</span></code> if no match can be found. If
they’re successful, a <a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> instance is returned,
containing information about the match: where it starts and ends, the substring
it matched, and more.</p>
<p>You can learn about this by interactively experimenting with the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a>
module. If you have <a class="reference internal" href="../library/tkinter.html#module-tkinter" title="tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">tkinter</span></code></a> available, you may also want to look at
<a class="reference external" href="https://github.com/python/cpython/tree/3.7/Tools/demo/redemo.py">Tools/demo/redemo.py</a>, a demonstration program included with the
Python distribution. It allows you to enter REs and strings, and displays
whether the RE matches or fails. <code class="file docutils literal notranslate"><span class="pre">redemo.py</span></code> can be quite useful when
trying to debug a complicated RE.</p>
<p>This HOWTO uses the standard Python interpreter for its examples. First, run the
Python interpreter, import the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module, and compile a RE:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">>>> </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">'[a-z]+'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">p</span>
<span class="go">re.compile('[a-z]+')</span>
</pre></div>
</div>
<p>Now, you can try matching various strings against the RE <code class="docutils literal notranslate"><span class="pre">[a-z]+</span></code>. An empty
string shouldn’t match at all, since <code class="docutils literal notranslate"><span class="pre">+</span></code> means 『one or more repetitions』.
<a class="reference internal" href="../library/re.html#re.Pattern.match" title="re.Pattern.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a> should return <code class="docutils literal notranslate"><span class="pre">None</span></code> in this case, which will cause the
interpreter to print no output. You can explicitly print the result of
<code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code> to make this clear.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">""</span><span class="p">)</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">""</span><span class="p">))</span>
<span class="go">None</span>
</pre></div>
</div>
<p>Now, let’s try it on a string that it should match, such as <code class="docutils literal notranslate"><span class="pre">tempo</span></code>. In this
case, <a class="reference internal" href="../library/re.html#re.Pattern.match" title="re.Pattern.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a> will return a <a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a>, so you
should store the result in a variable for later use.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">'tempo'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">m</span>
<span class="go"><re.Match object; span=(0, 5), match='tempo'></span>
</pre></div>
</div>
<p>Now you can query the <a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> for information
about the matching string. Match object instances
also have several methods and attributes; the most important ones are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="29%" />
<col width="71%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Method/Attribute</th>
<th class="head">Purpose</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">group()</span></code></td>
<td>Return the string matched by the RE</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">start()</span></code></td>
<td>Return the starting position of the match</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">end()</span></code></td>
<td>Return the ending position of the match</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">span()</span></code></td>
<td>Return a tuple containing the (start, end)
positions of the match</td>
</tr>
</tbody>
</table>
<p>Trying these methods will soon clarify their meaning:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">'tempo'</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">start</span><span class="p">(),</span> <span class="n">m</span><span class="o">.</span><span class="n">end</span><span class="p">()</span>
<span class="go">(0, 5)</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="go">(0, 5)</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/re.html#re.Match.group" title="re.Match.group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">group()</span></code></a> returns the substring that was matched by the RE. <a class="reference internal" href="../library/re.html#re.Match.start" title="re.Match.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code></a>
and <a class="reference internal" href="../library/re.html#re.Match.end" title="re.Match.end"><code class="xref py py-meth docutils literal notranslate"><span class="pre">end()</span></code></a> return the starting and ending index of the match. <a class="reference internal" href="../library/re.html#re.Match.span" title="re.Match.span"><code class="xref py py-meth docutils literal notranslate"><span class="pre">span()</span></code></a>
returns both start and end indexes in a single tuple. Since the <a class="reference internal" href="../library/re.html#re.Pattern.match" title="re.Pattern.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a>
method only checks if the RE matches at the start of a string, <code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code>
will always be zero. However, the <a class="reference internal" href="../library/re.html#re.Pattern.search" title="re.Pattern.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a> method of patterns
scans through the string, so the match may not start at zero in that
case.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">'::: message'</span><span class="p">))</span>
<span class="go">None</span>
<span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">'::: message'</span><span class="p">);</span> <span class="nb">print</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
<span class="go"><re.Match object; span=(4, 11), match='message'></span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">'message'</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="go">(4, 11)</span>
</pre></div>
</div>
<p>In actual programs, the most common style is to store the
<a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> in a variable, and then check if it was
<code class="docutils literal notranslate"><span class="pre">None</span></code>. This usually looks like:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span> <span class="o">...</span> <span class="p">)</span>
<span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span> <span class="s1">'string goes here'</span> <span class="p">)</span>
<span class="k">if</span> <span class="n">m</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'Match found: '</span><span class="p">,</span> <span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">())</span>
<span class="k">else</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">'No match'</span><span class="p">)</span>
</pre></div>
</div>
<p>Two pattern methods return all of the matches for a pattern.
<a class="reference internal" href="../library/re.html#re.Pattern.findall" title="re.Pattern.findall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">findall()</span></code></a> returns a list of matching strings:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">'\d+'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s1">'12 drummers drumming, 11 pipers piping, 10 lords a-leaping'</span><span class="p">)</span>
<span class="go">['12', '11', '10']</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">r</span></code> prefix, making the literal a raw string literal, is needed in this
example because escape sequences in a normal 「cooked」 string literal that are
not recognized by Python, as opposed to regular expressions, now result in a
<a class="reference internal" href="../library/exceptions.html#DeprecationWarning" title="DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> and will eventually become a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>. See
<a class="reference internal" href="#the-backslash-plague"><span class="std std-ref">The Backslash Plague</span></a>.</p>
<p><a class="reference internal" href="../library/re.html#re.Pattern.findall" title="re.Pattern.findall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">findall()</span></code></a> has to create the entire list before it can be returned as the
result. The <a class="reference internal" href="../library/re.html#re.Pattern.finditer" title="re.Pattern.finditer"><code class="xref py py-meth docutils literal notranslate"><span class="pre">finditer()</span></code></a> method returns a sequence of
<a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> instances as an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">iterator</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">finditer</span><span class="p">(</span><span class="s1">'12 drummers drumming, 11 ... 10 ...'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">iterator</span>
<span class="go"><callable_iterator object at 0x...></span>
<span class="gp">>>> </span><span class="k">for</span> <span class="n">match</span> <span class="ow">in</span> <span class="n">iterator</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">match</span><span class="o">.</span><span class="n">span</span><span class="p">())</span>
<span class="gp">...</span>
<span class="go">(0, 2)</span>
<span class="go">(22, 24)</span>
<span class="go">(29, 31)</span>
</pre></div>
</div>
</div>
<div class="section" id="module-level-functions">
<h3>Module-Level Functions<a class="headerlink" href="#module-level-functions" title="本標題的永久連結">¶</a></h3>
<p>You don’t have to create a pattern object and call its methods; the
<a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module also provides top-level functions called <a class="reference internal" href="../library/re.html#re.match" title="re.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">match()</span></code></a>,
<a class="reference internal" href="../library/re.html#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code></a>, <a class="reference internal" href="../library/re.html#re.findall" title="re.findall"><code class="xref py py-func docutils literal notranslate"><span class="pre">findall()</span></code></a>, <a class="reference internal" href="../library/re.html#re.sub" title="re.sub"><code class="xref py py-func docutils literal notranslate"><span class="pre">sub()</span></code></a>, and so forth. These functions
take the same arguments as the corresponding pattern method with
the RE string added as the first argument, and still return either <code class="docutils literal notranslate"><span class="pre">None</span></code> or a
<a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> instance.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s1">'From\s+'</span><span class="p">,</span> <span class="s1">'Fromage amk'</span><span class="p">))</span>
<span class="go">None</span>
<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s1">'From\s+'</span><span class="p">,</span> <span class="s1">'From amk Thu May 14 19:12:10 1998'</span><span class="p">)</span>
<span class="go"><re.Match object; span=(0, 5), match='From '></span>
</pre></div>
</div>
<p>Under the hood, these functions simply create a pattern object for you
and call the appropriate method on it. They also store the compiled
object in a cache, so future calls using the same RE won’t need to
parse the pattern again and again.</p>
<p>Should you use these module-level functions, or should you get the
pattern and call its methods yourself? If you’re accessing a regex
within a loop, pre-compiling it will save a few function calls.
Outside of loops, there’s not much difference thanks to the internal
cache.</p>
</div>
<div class="section" id="compilation-flags">
<h3>Compilation Flags<a class="headerlink" href="#compilation-flags" title="本標題的永久連結">¶</a></h3>
<p>Compilation flags let you modify some aspects of how regular expressions work.
Flags are available in the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module under two names, a long name such as
<code class="xref py py-const docutils literal notranslate"><span class="pre">IGNORECASE</span></code> and a short, one-letter form such as <code class="xref py py-const docutils literal notranslate"><span class="pre">I</span></code>. (If you’re
familiar with Perl’s pattern modifiers, the one-letter forms use the same
letters; the short form of <a class="reference internal" href="../library/re.html#re.VERBOSE" title="re.VERBOSE"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.VERBOSE</span></code></a> is <a class="reference internal" href="../library/re.html#re.X" title="re.X"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.X</span></code></a>, for example.)
Multiple flags can be specified by bitwise OR-ing them; <code class="docutils literal notranslate"><span class="pre">re.I</span> <span class="pre">|</span> <span class="pre">re.M</span></code> sets
both the <code class="xref py py-const docutils literal notranslate"><span class="pre">I</span></code> and <code class="xref py py-const docutils literal notranslate"><span class="pre">M</span></code> flags, for example.</p>
<p>Here’s a table of the available flags, followed by a more detailed explanation
of each one.</p>
<table border="1" class="docutils">
<colgroup>
<col width="43%" />
<col width="57%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Flag</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">ASCII</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">A</span></code></td>
<td>Makes several escapes like <code class="docutils literal notranslate"><span class="pre">\w</span></code>, <code class="docutils literal notranslate"><span class="pre">\b</span></code>,
<code class="docutils literal notranslate"><span class="pre">\s</span></code> and <code class="docutils literal notranslate"><span class="pre">\d</span></code> match only on ASCII
characters with the respective property.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">DOTALL</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">S</span></code></td>
<td>Make <code class="docutils literal notranslate"><span class="pre">.</span></code> match any character, including
newlines.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">IGNORECASE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">I</span></code></td>
<td>Do case-insensitive matches.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">L</span></code></td>
<td>Do a locale-aware match.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">M</span></code></td>
<td>Multi-line matching, affecting <code class="docutils literal notranslate"><span class="pre">^</span></code> and
<code class="docutils literal notranslate"><span class="pre">$</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">VERBOSE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">X</span></code>
(for 『extended』)</td>
<td>Enable verbose REs, which can be organized
more cleanly and understandably.</td>
</tr>
</tbody>
</table>
<dl class="data">
<dt>
<code class="descname">I</code></dt>
<dt>
<code class="descname">IGNORECASE</code></dt>
<dd><p>Perform case-insensitive matching; character class and literal strings will
match letters by ignoring case. For example, <code class="docutils literal notranslate"><span class="pre">[A-Z]</span></code> will match lowercase
letters, too. Full Unicode matching also works unless the <code class="xref py py-const docutils literal notranslate"><span class="pre">ASCII</span></code>
flag is used to disable non-ASCII matches. When the Unicode patterns
<code class="docutils literal notranslate"><span class="pre">[a-z]</span></code> or <code class="docutils literal notranslate"><span class="pre">[A-Z]</span></code> are used in combination with the <code class="xref py py-const docutils literal notranslate"><span class="pre">IGNORECASE</span></code>
flag, they will match the 52 ASCII letters and 4 additional non-ASCII
letters: 『İ』 (U+0130, Latin capital letter I with dot above), 『ı』 (U+0131,
Latin small letter dotless i), 『ſ』 (U+017F, Latin small letter long s) and
『K』 (U+212A, Kelvin sign). <code class="docutils literal notranslate"><span class="pre">Spam</span></code> will match <code class="docutils literal notranslate"><span class="pre">'Spam'</span></code>, <code class="docutils literal notranslate"><span class="pre">'spam'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'spAM'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'ſpam'</span></code> (the latter is matched only in Unicode mode).
This lowercasing doesn’t take the current locale into account;
it will if you also set the <code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code> flag.</p>
</dd></dl>
<dl class="data">
<dt>
<code class="descname">L</code></dt>
<dt>
<code class="descname">LOCALE</code></dt>
<dd><p>Make <code class="docutils literal notranslate"><span class="pre">\w</span></code>, <code class="docutils literal notranslate"><span class="pre">\W</span></code>, <code class="docutils literal notranslate"><span class="pre">\b</span></code>, <code class="docutils literal notranslate"><span class="pre">\B</span></code> and case-insensitive matching dependent
on the current locale instead of the Unicode database.</p>
<p>Locales are a feature of the C library intended to help in writing programs
that take account of language differences. For example, if you’re
processing encoded French text, you’d want to be able to write <code class="docutils literal notranslate"><span class="pre">\w+</span></code> to
match words, but <code class="docutils literal notranslate"><span class="pre">\w</span></code> only matches the character class <code class="docutils literal notranslate"><span class="pre">[A-Za-z]</span></code> in
bytes patterns; it won’t match bytes corresponding to <code class="docutils literal notranslate"><span class="pre">é</span></code> or <code class="docutils literal notranslate"><span class="pre">ç</span></code>.
If your system is configured properly and a French locale is selected,
certain C functions will tell the program that the byte corresponding to
<code class="docutils literal notranslate"><span class="pre">é</span></code> should also be considered a letter.
Setting the <code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code> flag when compiling a regular expression will cause
the resulting compiled object to use these C functions for <code class="docutils literal notranslate"><span class="pre">\w</span></code>; this is
slower, but also enables <code class="docutils literal notranslate"><span class="pre">\w+</span></code> to match French words as you’d expect.
The use of this flag is discouraged in Python 3 as the locale mechanism
is very unreliable, it only handles one 「culture」 at a time, and it only
works with 8-bit locales. Unicode matching is already enabled by default
in Python 3 for Unicode (str) patterns, and it is able to handle different
locales/languages.</p>
</dd></dl>
<dl class="data">
<dt>
<code class="descname">M</code></dt>
<dt>
<code class="descname">MULTILINE</code></dt>
<dd><p>(<code class="docutils literal notranslate"><span class="pre">^</span></code> and <code class="docutils literal notranslate"><span class="pre">$</span></code> haven’t been explained yet; they’ll be introduced in section
<a class="reference internal" href="#more-metacharacters"><span class="std std-ref">More Metacharacters</span></a>.)</p>
<p>Usually <code class="docutils literal notranslate"><span class="pre">^</span></code> matches only at the beginning of the string, and <code class="docutils literal notranslate"><span class="pre">$</span></code> matches
only at the end of the string and immediately before the newline (if any) at the
end of the string. When this flag is specified, <code class="docutils literal notranslate"><span class="pre">^</span></code> matches at the beginning
of the string and at the beginning of each line within the string, immediately
following each newline. Similarly, the <code class="docutils literal notranslate"><span class="pre">$</span></code> metacharacter matches either at
the end of the string and at the end of each line (immediately preceding each
newline).</p>
</dd></dl>
<dl class="data">
<dt>
<code class="descname">S</code></dt>
<dt>
<code class="descname">DOTALL</code></dt>
<dd><p>Makes the <code class="docutils literal notranslate"><span class="pre">'.'</span></code> special character match any character at all, including a
newline; without this flag, <code class="docutils literal notranslate"><span class="pre">'.'</span></code> will match anything <em>except</em> a newline.</p>
</dd></dl>
<dl class="data">
<dt>
<code class="descname">A</code></dt>
<dt>
<code class="descname">ASCII</code></dt>
<dd><p>Make <code class="docutils literal notranslate"><span class="pre">\w</span></code>, <code class="docutils literal notranslate"><span class="pre">\W</span></code>, <code class="docutils literal notranslate"><span class="pre">\b</span></code>, <code class="docutils literal notranslate"><span class="pre">\B</span></code>, <code class="docutils literal notranslate"><span class="pre">\s</span></code> and <code class="docutils literal notranslate"><span class="pre">\S</span></code> perform ASCII-only
matching instead of full Unicode matching. This is only meaningful for
Unicode patterns, and is ignored for byte patterns.</p>
</dd></dl>
<dl class="data">
<dt>
<code class="descname">X</code></dt>
<dt>
<code class="descname">VERBOSE</code></dt>
<dd><p>This flag allows you to write regular expressions that are more readable by
granting you more flexibility in how you can format them. When this flag has
been specified, whitespace within the RE string is ignored, except when the
whitespace is in a character class or preceded by an unescaped backslash; this
lets you organize and indent the RE more clearly. This flag also lets you put
comments within a RE that will be ignored by the engine; comments are marked by
a <code class="docutils literal notranslate"><span class="pre">'#'</span></code> that’s neither in a character class or preceded by an unescaped
backslash.</p>
<p>For example, here’s a RE that uses <a class="reference internal" href="../library/re.html#re.VERBOSE" title="re.VERBOSE"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.VERBOSE</span></code></a>; see how much easier it
is to read?</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">charref</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s2">"""</span>
<span class="s2"> &[#] # Start of a numeric entity reference</span>
<span class="s2"> (</span>
<span class="s2"> 0[0-7]+ # Octal form</span>
<span class="s2"> | [0-9]+ # Decimal form</span>
<span class="s2"> | x[0-9a-fA-F]+ # Hexadecimal form</span>
<span class="s2"> )</span>
<span class="s2"> ; # Trailing semicolon</span>
<span class="s2">"""</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">VERBOSE</span><span class="p">)</span>
</pre></div>
</div>
<p>Without the verbose setting, the RE would look like this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">charref</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s2">"&#(0[0-7]+"</span>
<span class="s2">"|[0-9]+"</span>
<span class="s2">"|x[0-9a-fA-F]+);"</span><span class="p">)</span>
</pre></div>
</div>
<p>In the above example, Python’s automatic concatenation of string literals has
been used to break up the RE into smaller pieces, but it’s still more difficult
to understand than the version using <a class="reference internal" href="../library/re.html#re.VERBOSE" title="re.VERBOSE"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.VERBOSE</span></code></a>.</p>
</dd></dl>
</div>
</div>
<div class="section" id="more-pattern-power">
<h2>More Pattern Power<a class="headerlink" href="#more-pattern-power" title="本標題的永久連結">¶</a></h2>
<p>So far we’ve only covered a part of the features of regular expressions. In
this section, we’ll cover some new metacharacters, and how to use groups to
retrieve portions of the text that was matched.</p>
<div class="section" id="more-metacharacters">
<span id="id2"></span><h3>More Metacharacters<a class="headerlink" href="#more-metacharacters" title="本標題的永久連結">¶</a></h3>
<p>There are some metacharacters that we haven’t covered yet. Most of them will be
covered in this section.</p>
<p>Some of the remaining metacharacters to be discussed are <em class="dfn">zero-width
assertions</em>. They don’t cause the engine to advance through the string;
instead, they consume no characters at all, and simply succeed or fail. For
example, <code class="docutils literal notranslate"><span class="pre">\b</span></code> is an assertion that the current position is located at a word
boundary; the position isn’t changed by the <code class="docutils literal notranslate"><span class="pre">\b</span></code> at all. This means that
zero-width assertions should never be repeated, because if they match once at a
given location, they can obviously be matched an infinite number of times.</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">|</span></code></dt>
<dd><p class="first">Alternation, or the 「or」 operator. If <em>A</em> and <em>B</em> are regular expressions,
<code class="docutils literal notranslate"><span class="pre">A|B</span></code> will match any string that matches either <em>A</em> or <em>B</em>. <code class="docutils literal notranslate"><span class="pre">|</span></code> has very
low precedence in order to make it work reasonably when you’re alternating
multi-character strings. <code class="docutils literal notranslate"><span class="pre">Crow|Servo</span></code> will match either <code class="docutils literal notranslate"><span class="pre">'Crow'</span></code> or <code class="docutils literal notranslate"><span class="pre">'Servo'</span></code>,
not <code class="docutils literal notranslate"><span class="pre">'Cro'</span></code>, a <code class="docutils literal notranslate"><span class="pre">'w'</span></code> or an <code class="docutils literal notranslate"><span class="pre">'S'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'ervo'</span></code>.</p>
<p class="last">To match a literal <code class="docutils literal notranslate"><span class="pre">'|'</span></code>, use <code class="docutils literal notranslate"><span class="pre">\|</span></code>, or enclose it inside a character class,
as in <code class="docutils literal notranslate"><span class="pre">[|]</span></code>.</p>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">^</span></code></dt>
<dd><p class="first">Matches at the beginning of lines. Unless the <code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code> flag has been
set, this will only match at the beginning of the string. In <code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code>
mode, this also matches immediately after each newline within the string.</p>
<p>For example, if you wish to match the word <code class="docutils literal notranslate"><span class="pre">From</span></code> only at the beginning of a
line, the RE to use is <code class="docutils literal notranslate"><span class="pre">^From</span></code>.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">'^From'</span><span class="p">,</span> <span class="s1">'From Here to Eternity'</span><span class="p">))</span>
<span class="go"><re.Match object; span=(0, 4), match='From'></span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">'^From'</span><span class="p">,</span> <span class="s1">'Reciting From Memory'</span><span class="p">))</span>
<span class="go">None</span>
</pre></div>
</div>
<p class="last">To match a literal <code class="docutils literal notranslate"><span class="pre">'^'</span></code>, use <code class="docutils literal notranslate"><span class="pre">\^</span></code>.</p>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">$</span></code></dt>
<dd><p class="first">Matches at the end of a line, which is defined as either the end of the string,
or any location followed by a newline character.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">'}$'</span><span class="p">,</span> <span class="s1">'</span><span class="si">{block}</span><span class="s1">'</span><span class="p">))</span>
<span class="go"><re.Match object; span=(6, 7), match='}'></span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">'}$'</span><span class="p">,</span> <span class="s1">'</span><span class="si">{block}</span><span class="s1"> '</span><span class="p">))</span>
<span class="go">None</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">'}$'</span><span class="p">,</span> <span class="s1">'</span><span class="si">{block}</span><span class="se">\n</span><span class="s1">'</span><span class="p">))</span>
<span class="go"><re.Match object; span=(6, 7), match='}'></span>
</pre></div>
</div>
<p class="last">To match a literal <code class="docutils literal notranslate"><span class="pre">'$'</span></code>, use <code class="docutils literal notranslate"><span class="pre">\$</span></code> or enclose it inside a character class,
as in <code class="docutils literal notranslate"><span class="pre">[$]</span></code>.</p>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\A</span></code></dt>
<dd>Matches only at the start of the string. When not in <code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code> mode,
<code class="docutils literal notranslate"><span class="pre">\A</span></code> and <code class="docutils literal notranslate"><span class="pre">^</span></code> are effectively the same. In <code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code> mode, they’re
different: <code class="docutils literal notranslate"><span class="pre">\A</span></code> still matches only at the beginning of the string, but <code class="docutils literal notranslate"><span class="pre">^</span></code>
may match at any location inside the string that follows a newline character.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\Z</span></code></dt>
<dd>Matches only at the end of the string.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\b</span></code></dt>
<dd><p class="first">Word boundary. This is a zero-width assertion that matches only at the
beginning or end of a word. A word is defined as a sequence of alphanumeric
characters, so the end of a word is indicated by whitespace or a
non-alphanumeric character.</p>
<p>The following example matches <code class="docutils literal notranslate"><span class="pre">class</span></code> only when it’s a complete word; it won’t
match when it’s contained inside another word.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">'\bclass\b'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">'no class at all'</span><span class="p">))</span>
<span class="go"><re.Match object; span=(3, 8), match='class'></span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">'the declassified algorithm'</span><span class="p">))</span>
<span class="go">None</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">'one subclass is'</span><span class="p">))</span>
<span class="go">None</span>
</pre></div>
</div>
<p>There are two subtleties you should remember when using this special sequence.
First, this is the worst collision between Python’s string literals and regular
expression sequences. In Python’s string literals, <code class="docutils literal notranslate"><span class="pre">\b</span></code> is the backspace
character, ASCII value 8. If you’re not using raw strings, then Python will
convert the <code class="docutils literal notranslate"><span class="pre">\b</span></code> to a backspace, and your RE won’t match as you expect it to.
The following example looks the same as our previous RE, but omits the <code class="docutils literal notranslate"><span class="pre">'r'</span></code>
in front of the RE string.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">'</span><span class="se">\b</span><span class="s1">class</span><span class="se">\b</span><span class="s1">'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">'no class at all'</span><span class="p">))</span>
<span class="go">None</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">'</span><span class="se">\b</span><span class="s1">'</span> <span class="o">+</span> <span class="s1">'class'</span> <span class="o">+</span> <span class="s1">'</span><span class="se">\b</span><span class="s1">'</span><span class="p">))</span>
<span class="go"><re.Match object; span=(0, 7), match='\x08class\x08'></span>
</pre></div>
</div>
<p class="last">Second, inside a character class, where there’s no use for this assertion,
<code class="docutils literal notranslate"><span class="pre">\b</span></code> represents the backspace character, for compatibility with Python’s
string literals.</p>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\B</span></code></dt>
<dd>Another zero-width assertion, this is the opposite of <code class="docutils literal notranslate"><span class="pre">\b</span></code>, only matching when
the current position is not at a word boundary.</dd>
</dl>
</div>
<div class="section" id="grouping">
<h3>Grouping<a class="headerlink" href="#grouping" title="本標題的永久連結">¶</a></h3>
<p>Frequently you need to obtain more information than just whether the RE matched
or not. Regular expressions are often used to dissect strings by writing a RE
divided into several subgroups which match different components of interest.
For example, an RFC-822 header line is divided into a header name and a value,
separated by a <code class="docutils literal notranslate"><span class="pre">':'</span></code>, like this:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>From: author@example.com
User-Agent: Thunderbird 1.5.0.9 (X11/20061227)
MIME-Version: 1.0
To: editor@example.com
</pre></div>
</div>
<p>This can be handled by writing a regular expression which matches an entire
header line, and has one group which matches the header name, and another group
which matches the header’s value.</p>
<p>Groups are marked by the <code class="docutils literal notranslate"><span class="pre">'('</span></code>, <code class="docutils literal notranslate"><span class="pre">')'</span></code> metacharacters. <code class="docutils literal notranslate"><span class="pre">'('</span></code> and <code class="docutils literal notranslate"><span class="pre">')'</span></code>
have much the same meaning as they do in mathematical expressions; they group
together the expressions contained inside them, and you can repeat the contents
of a group with a repeating qualifier, such as <code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">+</span></code>, <code class="docutils literal notranslate"><span class="pre">?</span></code>, or
<code class="docutils literal notranslate"><span class="pre">{m,n}</span></code>. For example, <code class="docutils literal notranslate"><span class="pre">(ab)*</span></code> will match zero or more repetitions of
<code class="docutils literal notranslate"><span class="pre">ab</span></code>.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">'(ab)*'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">'ababababab'</span><span class="p">)</span><span class="o">.</span><span class="n">span</span><span class="p">())</span>
<span class="go">(0, 10)</span>
</pre></div>
</div>
<p>Groups indicated with <code class="docutils literal notranslate"><span class="pre">'('</span></code>, <code class="docutils literal notranslate"><span class="pre">')'</span></code> also capture the starting and ending
index of the text that they match; this can be retrieved by passing an argument
to <a class="reference internal" href="../library/re.html#re.Match.group" title="re.Match.group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">group()</span></code></a>, <a class="reference internal" href="../library/re.html#re.Match.start" title="re.Match.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code></a>, <a class="reference internal" href="../library/re.html#re.Match.end" title="re.Match.end"><code class="xref py py-meth docutils literal notranslate"><span class="pre">end()</span></code></a>, and
<a class="reference internal" href="../library/re.html#re.Match.span" title="re.Match.span"><code class="xref py py-meth docutils literal notranslate"><span class="pre">span()</span></code></a>. Groups are
numbered starting with 0. Group 0 is always present; it’s the whole RE, so
<a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> methods all have group 0 as their default
argument. Later we’ll see how to express groups that don’t capture the span
of text that they match.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">'(a)b'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">'ab'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">'ab'</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">'ab'</span>
</pre></div>
</div>
<p>Subgroups are numbered from left to right, from 1 upward. Groups can be nested;
to determine the number, just count the opening parenthesis characters, going
from left to right.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">'(a(b)c)d'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">'abcd'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">'abcd'</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">'abc'</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="go">'b'</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/re.html#re.Match.group" title="re.Match.group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">group()</span></code></a> can be passed multiple group numbers at a time, in which case it
will return a tuple containing the corresponding values for those groups.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">)</span>
<span class="go">('b', 'abc', 'b')</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/re.html#re.Match.groups" title="re.Match.groups"><code class="xref py py-meth docutils literal notranslate"><span class="pre">groups()</span></code></a> method returns a tuple containing the strings for all the
subgroups, from 1 up to however many there are.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
<span class="go">('abc', 'b')</span>
</pre></div>
</div>
<p>Backreferences in a pattern allow you to specify that the contents of an earlier
capturing group must also be found at the current location in the string. For
example, <code class="docutils literal notranslate"><span class="pre">\1</span></code> will succeed if the exact contents of group 1 can be found at
the current position, and fails otherwise. Remember that Python’s string
literals also use a backslash followed by numbers to allow including arbitrary
characters in a string, so be sure to use a raw string when incorporating
backreferences in a RE.</p>
<p>For example, the following RE detects doubled words in a string.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">'\b(\w+)\s+\1\b'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">'Paris in the the spring'</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">'the the'</span>
</pre></div>
</div>
<p>Backreferences like this aren’t often useful for just searching through a string
— there are few text formats which repeat data in this way — but you’ll soon
find out that they’re <em>very</em> useful when performing string substitutions.</p>
</div>
<div class="section" id="non-capturing-and-named-groups">
<h3>Non-capturing and Named Groups<a class="headerlink" href="#non-capturing-and-named-groups" title="本標題的永久連結">¶</a></h3>
<p>Elaborate REs may use many groups, both to capture substrings of interest, and
to group and structure the RE itself. In complex REs, it becomes difficult to
keep track of the group numbers. There are two features which help with this
problem. Both of them use a common syntax for regular expression extensions, so
we’ll look at that first.</p>
<p>Perl 5 is well known for its powerful additions to standard regular expressions.
For these new features the Perl developers couldn’t choose new single-keystroke metacharacters
or new special sequences beginning with <code class="docutils literal notranslate"><span class="pre">\</span></code> without making Perl’s regular
expressions confusingly different from standard REs. If they chose <code class="docutils literal notranslate"><span class="pre">&</span></code> as a
new metacharacter, for example, old expressions would be assuming that <code class="docutils literal notranslate"><span class="pre">&</span></code> was
a regular character and wouldn’t have escaped it by writing <code class="docutils literal notranslate"><span class="pre">\&</span></code> or <code class="docutils literal notranslate"><span class="pre">[&]</span></code>.</p>
<p>The solution chosen by the Perl developers was to use <code class="docutils literal notranslate"><span class="pre">(?...)</span></code> as the
extension syntax. <code class="docutils literal notranslate"><span class="pre">?</span></code> immediately after a parenthesis was a syntax error
because the <code class="docutils literal notranslate"><span class="pre">?</span></code> would have nothing to repeat, so this didn’t introduce any
compatibility problems. The characters immediately after the <code class="docutils literal notranslate"><span class="pre">?</span></code> indicate
what extension is being used, so <code class="docutils literal notranslate"><span class="pre">(?=foo)</span></code> is one thing (a positive lookahead
assertion) and <code class="docutils literal notranslate"><span class="pre">(?:foo)</span></code> is something else (a non-capturing group containing
the subexpression <code class="docutils literal notranslate"><span class="pre">foo</span></code>).</p>
<p>Python supports several of Perl’s extensions and adds an extension
syntax to Perl’s extension syntax. If the first character after the
question mark is a <code class="docutils literal notranslate"><span class="pre">P</span></code>, you know that it’s an extension that’s
specific to Python.</p>
<p>Now that we’ve looked at the general extension syntax, we can return
to the features that simplify working with groups in complex REs.</p>
<p>Sometimes you’ll want to use a group to denote a part of a regular expression,
but aren’t interested in retrieving the group’s contents. You can make this fact
explicit by using a non-capturing group: <code class="docutils literal notranslate"><span class="pre">(?:...)</span></code>, where you can replace the
<code class="docutils literal notranslate"><span class="pre">...</span></code> with any other regular expression.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">"([abc])+"</span><span class="p">,</span> <span class="s2">"abc"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
<span class="go">('c',)</span>
<span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">"(?:[abc])+"</span><span class="p">,</span> <span class="s2">"abc"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
<span class="go">()</span>
</pre></div>
</div>
<p>Except for the fact that you can’t retrieve the contents of what the group
matched, a non-capturing group behaves exactly the same as a capturing group;
you can put anything inside it, repeat it with a repetition metacharacter such
as <code class="docutils literal notranslate"><span class="pre">*</span></code>, and nest it within other groups (capturing or non-capturing).
<code class="docutils literal notranslate"><span class="pre">(?:...)</span></code> is particularly useful when modifying an existing pattern, since you
can add new groups without changing how all the other groups are numbered. It
should be mentioned that there’s no performance difference in searching between
capturing and non-capturing groups; neither form is any faster than the other.</p>
<p>A more significant feature is named groups: instead of referring to them by