This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Some typo fixes reported by Tom Christiansen
[perl5.git] / pod / perlretut.pod
1 =head1 NAME
2
3 perlretut - Perl regular expressions tutorial
4
5 =head1 DESCRIPTION
6
7 This page provides a basic tutorial on understanding, creating and
8 using regular expressions in Perl.  It serves as a complement to the
9 reference page on regular expressions L<perlre>.  Regular expressions
10 are an integral part of the C<m//>, C<s///>, C<qr//> and C<split>
11 operators and so this tutorial also overlaps with
12 L<perlop/"Regexp Quote-Like Operators"> and L<perlfunc/split>.
13
14 Perl is widely renowned for excellence in text processing, and regular
15 expressions are one of the big factors behind this fame.  Perl regular
16 expressions display an efficiency and flexibility unknown in most
17 other computer languages.  Mastering even the basics of regular
18 expressions will allow you to manipulate text with surprising ease.
19
20 What is a regular expression?  A regular expression is simply a string
21 that describes a pattern.  Patterns are in common use these days;
22 examples are the patterns typed into a search engine to find web pages
23 and the patterns used to list files in a directory, e.g., C<ls *.txt>
24 or C<dir *.*>.  In Perl, the patterns described by regular expressions
25 are used to search strings, extract desired parts of strings, and to
26 do search and replace operations.
27
28 Regular expressions have the undeserved reputation of being abstract
29 and difficult to understand.  Regular expressions are constructed using
30 simple concepts like conditionals and loops and are no more difficult
31 to understand than the corresponding C<if> conditionals and C<while>
32 loops in the Perl language itself.  In fact, the main challenge in
33 learning regular expressions is just getting used to the terse
34 notation used to express these concepts.
35
36 This tutorial flattens the learning curve by discussing regular
37 expression concepts, along with their notation, one at a time and with
38 many examples.  The first part of the tutorial will progress from the
39 simplest word searches to the basic regular expression concepts.  If
40 you master the first part, you will have all the tools needed to solve
41 about 98% of your needs.  The second part of the tutorial is for those
42 comfortable with the basics and hungry for more power tools.  It
43 discusses the more advanced regular expression operators and
44 introduces the latest cutting edge innovations in 5.6.0.
45
46 A note: to save time, 'regular expression' is often abbreviated as
47 regexp or regex.  Regexp is a more natural abbreviation than regex, but
48 is harder to pronounce.  The Perl pod documentation is evenly split on
49 regexp vs regex; in Perl, there is more than one way to abbreviate it.
50 We'll use regexp in this tutorial.
51
52 =head1 Part 1: The basics
53
54 =head2 Simple word matching
55
56 The simplest regexp is simply a word, or more generally, a string of
57 characters.  A regexp consisting of a word matches any string that
58 contains that word:
59
60     "Hello World" =~ /World/;  # matches
61
62 What is this Perl statement all about? C<"Hello World"> is a simple
63 double quoted string.  C<World> is the regular expression and the
64 C<//> enclosing C</World/> tells Perl to search a string for a match.
65 The operator C<=~> associates the string with the regexp match and
66 produces a true value if the regexp matched, or false if the regexp
67 did not match.  In our case, C<World> matches the second word in
68 C<"Hello World">, so the expression is true.  Expressions like this
69 are useful in conditionals:
70
71     if ("Hello World" =~ /World/) {
72         print "It matches\n";
73     }
74     else {
75         print "It doesn't match\n";
76     }
77
78 There are useful variations on this theme.  The sense of the match can
79 be reversed by using the C<!~> operator:
80
81     if ("Hello World" !~ /World/) {
82         print "It doesn't match\n";
83     }
84     else {
85         print "It matches\n";
86     }
87
88 The literal string in the regexp can be replaced by a variable:
89
90     $greeting = "World";
91     if ("Hello World" =~ /$greeting/) {
92         print "It matches\n";
93     }
94     else {
95         print "It doesn't match\n";
96     }
97
98 If you're matching against the special default variable C<$_>, the
99 C<$_ =~> part can be omitted:
100
101     $_ = "Hello World";
102     if (/World/) {
103         print "It matches\n";
104     }
105     else {
106         print "It doesn't match\n";
107     }
108
109 And finally, the C<//> default delimiters for a match can be changed
110 to arbitrary delimiters by putting an C<'m'> out front:
111
112     "Hello World" =~ m!World!;   # matches, delimited by '!'
113     "Hello World" =~ m{World};   # matches, note the matching '{}'
114     "/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin',
115                                  # '/' becomes an ordinary char
116
117 C</World/>, C<m!World!>, and C<m{World}> all represent the
118 same thing.  When, e.g., the quote (C<">) is used as a delimiter, the forward
119 slash C<'/'> becomes an ordinary character and can be used in this regexp
120 without trouble.
121
122 Let's consider how different regexps would match C<"Hello World">:
123
124     "Hello World" =~ /world/;  # doesn't match
125     "Hello World" =~ /o W/;    # matches
126     "Hello World" =~ /oW/;     # doesn't match
127     "Hello World" =~ /World /; # doesn't match
128
129 The first regexp C<world> doesn't match because regexps are
130 case-sensitive.  The second regexp matches because the substring
131 S<C<'o W'>> occurs in the string S<C<"Hello World">>.  The space
132 character ' ' is treated like any other character in a regexp and is
133 needed to match in this case.  The lack of a space character is the
134 reason the third regexp C<'oW'> doesn't match.  The fourth regexp
135 C<'World '> doesn't match because there is a space at the end of the
136 regexp, but not at the end of the string.  The lesson here is that
137 regexps must match a part of the string I<exactly> in order for the
138 statement to be true.
139
140 If a regexp matches in more than one place in the string, Perl will
141 always match at the earliest possible point in the string:
142
143     "Hello World" =~ /o/;       # matches 'o' in 'Hello'
144     "That hat is red" =~ /hat/; # matches 'hat' in 'That'
145
146 With respect to character matching, there are a few more points you
147 need to know about.   First of all, not all characters can be used 'as
148 is' in a match.  Some characters, called I<metacharacters>, are reserved
149 for use in regexp notation.  The metacharacters are
150
151     {}[]()^$.|*+?\
152
153 The significance of each of these will be explained
154 in the rest of the tutorial, but for now, it is important only to know
155 that a metacharacter can be matched by putting a backslash before it:
156
157     "2+2=4" =~ /2+2/;    # doesn't match, + is a metacharacter
158     "2+2=4" =~ /2\+2/;   # matches, \+ is treated like an ordinary +
159     "The interval is [0,1)." =~ /[0,1)./     # is a syntax error!
160     "The interval is [0,1)." =~ /\[0,1\)\./  # matches
161     "#!/usr/bin/perl" =~ /#!\/usr\/bin\/perl/;  # matches
162
163 In the last regexp, the forward slash C<'/'> is also backslashed,
164 because it is used to delimit the regexp.  This can lead to LTS
165 (leaning toothpick syndrome), however, and it is often more readable
166 to change delimiters.
167
168     "#!/usr/bin/perl" =~ m!#\!/usr/bin/perl!;  # easier to read
169
170 The backslash character C<'\'> is a metacharacter itself and needs to
171 be backslashed:
172
173     'C:\WIN32' =~ /C:\\WIN/;   # matches
174
175 In addition to the metacharacters, there are some ASCII characters
176 which don't have printable character equivalents and are instead
177 represented by I<escape sequences>.  Common examples are C<\t> for a
178 tab, C<\n> for a newline, C<\r> for a carriage return and C<\a> for a
179 bell.  If your string is better thought of as a sequence of arbitrary
180 bytes, the octal escape sequence, e.g., C<\033>, or hexadecimal escape
181 sequence, e.g., C<\x1B> may be a more natural representation for your
182 bytes.  Here are some examples of escapes:
183
184     "1000\t2000" =~ m(0\t2)   # matches
185     "1000\n2000" =~ /0\n20/   # matches
186     "1000\t2000" =~ /\000\t2/ # doesn't match, "0" ne "\000"
187     "cat"   =~ /\o{143}\x61\x74/ # matches in ASCII, but a weird way
188                                  # to spell cat
189
190 If you've been around Perl a while, all this talk of escape sequences
191 may seem familiar.  Similar escape sequences are used in double-quoted
192 strings and in fact the regexps in Perl are mostly treated as
193 double-quoted strings.  This means that variables can be used in
194 regexps as well.  Just like double-quoted strings, the values of the
195 variables in the regexp will be substituted in before the regexp is
196 evaluated for matching purposes.  So we have:
197
198     $foo = 'house';
199     'housecat' =~ /$foo/;      # matches
200     'cathouse' =~ /cat$foo/;   # matches
201     'housecat' =~ /${foo}cat/; # matches
202
203 So far, so good.  With the knowledge above you can already perform
204 searches with just about any literal string regexp you can dream up.
205 Here is a I<very simple> emulation of the Unix grep program:
206
207     % cat > simple_grep
208     #!/usr/bin/perl
209     $regexp = shift;
210     while (<>) {
211         print if /$regexp/;
212     }
213     ^D
214
215     % chmod +x simple_grep
216
217     % simple_grep abba /usr/dict/words
218     Babbage
219     cabbage
220     cabbages
221     sabbath
222     Sabbathize
223     Sabbathizes
224     sabbatical
225     scabbard
226     scabbards
227
228 This program is easy to understand.  C<#!/usr/bin/perl> is the standard
229 way to invoke a perl program from the shell.
230 S<C<$regexp = shift;>> saves the first command line argument as the
231 regexp to be used, leaving the rest of the command line arguments to
232 be treated as files.  S<C<< while (<>) >>> loops over all the lines in
233 all the files.  For each line, S<C<print if /$regexp/;>> prints the
234 line if the regexp matches the line.  In this line, both C<print> and
235 C</$regexp/> use the default variable C<$_> implicitly.
236
237 With all of the regexps above, if the regexp matched anywhere in the
238 string, it was considered a match.  Sometimes, however, we'd like to
239 specify I<where> in the string the regexp should try to match.  To do
240 this, we would use the I<anchor> metacharacters C<^> and C<$>.  The
241 anchor C<^> means match at the beginning of the string and the anchor
242 C<$> means match at the end of the string, or before a newline at the
243 end of the string.  Here is how they are used:
244
245     "housekeeper" =~ /keeper/;    # matches
246     "housekeeper" =~ /^keeper/;   # doesn't match
247     "housekeeper" =~ /keeper$/;   # matches
248     "housekeeper\n" =~ /keeper$/; # matches
249
250 The second regexp doesn't match because C<^> constrains C<keeper> to
251 match only at the beginning of the string, but C<"housekeeper"> has
252 keeper starting in the middle.  The third regexp does match, since the
253 C<$> constrains C<keeper> to match only at the end of the string.
254
255 When both C<^> and C<$> are used at the same time, the regexp has to
256 match both the beginning and the end of the string, i.e., the regexp
257 matches the whole string.  Consider
258
259     "keeper" =~ /^keep$/;      # doesn't match
260     "keeper" =~ /^keeper$/;    # matches
261     ""       =~ /^$/;          # ^$ matches an empty string
262
263 The first regexp doesn't match because the string has more to it than
264 C<keep>.  Since the second regexp is exactly the string, it
265 matches.  Using both C<^> and C<$> in a regexp forces the complete
266 string to match, so it gives you complete control over which strings
267 match and which don't.  Suppose you are looking for a fellow named
268 bert, off in a string by himself:
269
270     "dogbert" =~ /bert/;   # matches, but not what you want
271
272     "dilbert" =~ /^bert/;  # doesn't match, but ..
273     "bertram" =~ /^bert/;  # matches, so still not good enough
274
275     "bertram" =~ /^bert$/; # doesn't match, good
276     "dilbert" =~ /^bert$/; # doesn't match, good
277     "bert"    =~ /^bert$/; # matches, perfect
278
279 Of course, in the case of a literal string, one could just as easily
280 use the string comparison S<C<$string eq 'bert'>> and it would be
281 more efficient.   The  C<^...$> regexp really becomes useful when we
282 add in the more powerful regexp tools below.
283
284 =head2 Using character classes
285
286 Although one can already do quite a lot with the literal string
287 regexps above, we've only scratched the surface of regular expression
288 technology.  In this and subsequent sections we will introduce regexp
289 concepts (and associated metacharacter notations) that will allow a
290 regexp to not just represent a single character sequence, but a I<whole
291 class> of them.
292
293 One such concept is that of a I<character class>.  A character class
294 allows a set of possible characters, rather than just a single
295 character, to match at a particular point in a regexp.  Character
296 classes are denoted by brackets C<[...]>, with the set of characters
297 to be possibly matched inside.  Here are some examples:
298
299     /cat/;       # matches 'cat'
300     /[bcr]at/;   # matches 'bat, 'cat', or 'rat'
301     /item[0123456789]/;  # matches 'item0' or ... or 'item9'
302     "abc" =~ /[cab]/;    # matches 'a'
303
304 In the last statement, even though C<'c'> is the first character in
305 the class, C<'a'> matches because the first character position in the
306 string is the earliest point at which the regexp can match.
307
308     /[yY][eE][sS]/;      # match 'yes' in a case-insensitive way
309                          # 'yes', 'Yes', 'YES', etc.
310
311 This regexp displays a common task: perform a case-insensitive
312 match.  Perl provides a way of avoiding all those brackets by simply
313 appending an C<'i'> to the end of the match.  Then C</[yY][eE][sS]/;>
314 can be rewritten as C</yes/i;>.  The C<'i'> stands for
315 case-insensitive and is an example of a I<modifier> of the matching
316 operation.  We will meet other modifiers later in the tutorial.
317
318 We saw in the section above that there were ordinary characters, which
319 represented themselves, and special characters, which needed a
320 backslash C<\> to represent themselves.  The same is true in a
321 character class, but the sets of ordinary and special characters
322 inside a character class are different than those outside a character
323 class.  The special characters for a character class are C<-]\^$> (and
324 the pattern delimiter, whatever it is).
325 C<]> is special because it denotes the end of a character class.  C<$> is
326 special because it denotes a scalar variable.  C<\> is special because
327 it is used in escape sequences, just like above.  Here is how the
328 special characters C<]$\> are handled:
329
330    /[\]c]def/; # matches ']def' or 'cdef'
331    $x = 'bcr';
332    /[$x]at/;   # matches 'bat', 'cat', or 'rat'
333    /[\$x]at/;  # matches '$at' or 'xat'
334    /[\\$x]at/; # matches '\at', 'bat, 'cat', or 'rat'
335
336 The last two are a little tricky.  In C<[\$x]>, the backslash protects
337 the dollar sign, so the character class has two members C<$> and C<x>.
338 In C<[\\$x]>, the backslash is protected, so C<$x> is treated as a
339 variable and substituted in double quote fashion.
340
341 The special character C<'-'> acts as a range operator within character
342 classes, so that a contiguous set of characters can be written as a
343 range.  With ranges, the unwieldy C<[0123456789]> and C<[abc...xyz]>
344 become the svelte C<[0-9]> and C<[a-z]>.  Some examples are
345
346     /item[0-9]/;  # matches 'item0' or ... or 'item9'
347     /[0-9bx-z]aa/;  # matches '0aa', ..., '9aa',
348                     # 'baa', 'xaa', 'yaa', or 'zaa'
349     /[0-9a-fA-F]/;  # matches a hexadecimal digit
350     /[0-9a-zA-Z_]/; # matches a "word" character,
351                     # like those in a Perl variable name
352
353 If C<'-'> is the first or last character in a character class, it is
354 treated as an ordinary character; C<[-ab]>, C<[ab-]> and C<[a\-b]> are
355 all equivalent.
356
357 The special character C<^> in the first position of a character class
358 denotes a I<negated character class>, which matches any character but
359 those in the brackets.  Both C<[...]> and C<[^...]> must match a
360 character, or the match fails.  Then
361
362     /[^a]at/;  # doesn't match 'aat' or 'at', but matches
363                # all other 'bat', 'cat, '0at', '%at', etc.
364     /[^0-9]/;  # matches a non-numeric character
365     /[a^]at/;  # matches 'aat' or '^at'; here '^' is ordinary
366
367 Now, even C<[0-9]> can be a bother to write multiple times, so in the
368 interest of saving keystrokes and making regexps more readable, Perl
369 has several abbreviations for common character classes, as shown below.
370 Since the introduction of Unicode, these character classes match more
371 than just a few characters in the ISO 8859-1 range.
372
373 =over 4
374
375 =item *
376
377 \d matches a digit, not just [0-9] but also digits from non-roman scripts
378
379 =item *
380
381 \s matches a whitespace character, the set [\ \t\r\n\f] and others
382
383 =item *
384
385 \w matches a word character (alphanumeric or _), not just [0-9a-zA-Z_]
386 but also digits and characters from non-roman scripts
387
388 =item *
389
390 \D is a negated \d; it represents any other character than a digit, or [^\d]
391
392 =item *
393
394 \S is a negated \s; it represents any non-whitespace character [^\s]
395
396 =item *
397
398 \W is a negated \w; it represents any non-word character [^\w]
399
400 =item *
401
402 The period '.' matches any character but "\n" (unless the modifier C<//s> is
403 in effect, as explained below).
404
405 =back
406
407 The C<\d\s\w\D\S\W> abbreviations can be used both inside and outside
408 of character classes.  Here are some in use:
409
410     /\d\d:\d\d:\d\d/; # matches a hh:mm:ss time format
411     /[\d\s]/;         # matches any digit or whitespace character
412     /\w\W\w/;         # matches a word char, followed by a
413                       # non-word char, followed by a word char
414     /..rt/;           # matches any two chars, followed by 'rt'
415     /end\./;          # matches 'end.'
416     /end[.]/;         # same thing, matches 'end.'
417
418 Because a period is a metacharacter, it needs to be escaped to match
419 as an ordinary period. Because, for example, C<\d> and C<\w> are sets
420 of characters, it is incorrect to think of C<[^\d\w]> as C<[\D\W]>; in
421 fact C<[^\d\w]> is the same as C<[^\w]>, which is the same as
422 C<[\W]>. Think DeMorgan's laws.
423
424 An anchor useful in basic regexps is the I<word anchor>
425 C<\b>.  This matches a boundary between a word character and a non-word
426 character C<\w\W> or C<\W\w>:
427
428     $x = "Housecat catenates house and cat";
429     $x =~ /cat/;    # matches cat in 'housecat'
430     $x =~ /\bcat/;  # matches cat in 'catenates'
431     $x =~ /cat\b/;  # matches cat in 'housecat'
432     $x =~ /\bcat\b/;  # matches 'cat' at end of string
433
434 Note in the last example, the end of the string is considered a word
435 boundary.
436
437 You might wonder why C<'.'> matches everything but C<"\n"> - why not
438 every character? The reason is that often one is matching against
439 lines and would like to ignore the newline characters.  For instance,
440 while the string C<"\n"> represents one line, we would like to think
441 of it as empty.  Then
442
443     ""   =~ /^$/;    # matches
444     "\n" =~ /^$/;    # matches, $ anchors before "\n"
445
446     ""   =~ /./;      # doesn't match; it needs a char
447     ""   =~ /^.$/;    # doesn't match; it needs a char
448     "\n" =~ /^.$/;    # doesn't match; it needs a char other than "\n"
449     "a"  =~ /^.$/;    # matches
450     "a\n"  =~ /^.$/;  # matches, $ anchors before "\n"
451
452 This behavior is convenient, because we usually want to ignore
453 newlines when we count and match characters in a line.  Sometimes,
454 however, we want to keep track of newlines.  We might even want C<^>
455 and C<$> to anchor at the beginning and end of lines within the
456 string, rather than just the beginning and end of the string.  Perl
457 allows us to choose between ignoring and paying attention to newlines
458 by using the C<//s> and C<//m> modifiers.  C<//s> and C<//m> stand for
459 single line and multi-line and they determine whether a string is to
460 be treated as one continuous string, or as a set of lines.  The two
461 modifiers affect two aspects of how the regexp is interpreted: 1) how
462 the C<'.'> character class is defined, and 2) where the anchors C<^>
463 and C<$> are able to match.  Here are the four possible combinations:
464
465 =over 4
466
467 =item *
468
469 no modifiers (//): Default behavior.  C<'.'> matches any character
470 except C<"\n">.  C<^> matches only at the beginning of the string and
471 C<$> matches only at the end or before a newline at the end.
472
473 =item *
474
475 s modifier (//s): Treat string as a single long line.  C<'.'> matches
476 any character, even C<"\n">.  C<^> matches only at the beginning of
477 the string and C<$> matches only at the end or before a newline at the
478 end.
479
480 =item *
481
482 m modifier (//m): Treat string as a set of multiple lines.  C<'.'>
483 matches any character except C<"\n">.  C<^> and C<$> are able to match
484 at the start or end of I<any> line within the string.
485
486 =item *
487
488 both s and m modifiers (//sm): Treat string as a single long line, but
489 detect multiple lines.  C<'.'> matches any character, even
490 C<"\n">.  C<^> and C<$>, however, are able to match at the start or end
491 of I<any> line within the string.
492
493 =back
494
495 Here are examples of C<//s> and C<//m> in action:
496
497     $x = "There once was a girl\nWho programmed in Perl\n";
498
499     $x =~ /^Who/;   # doesn't match, "Who" not at start of string
500     $x =~ /^Who/s;  # doesn't match, "Who" not at start of string
501     $x =~ /^Who/m;  # matches, "Who" at start of second line
502     $x =~ /^Who/sm; # matches, "Who" at start of second line
503
504     $x =~ /girl.Who/;   # doesn't match, "." doesn't match "\n"
505     $x =~ /girl.Who/s;  # matches, "." matches "\n"
506     $x =~ /girl.Who/m;  # doesn't match, "." doesn't match "\n"
507     $x =~ /girl.Who/sm; # matches, "." matches "\n"
508
509 Most of the time, the default behavior is what is wanted, but C<//s> and
510 C<//m> are occasionally very useful.  If C<//m> is being used, the start
511 of the string can still be matched with C<\A> and the end of the string
512 can still be matched with the anchors C<\Z> (matches both the end and
513 the newline before, like C<$>), and C<\z> (matches only the end):
514
515     $x =~ /^Who/m;   # matches, "Who" at start of second line
516     $x =~ /\AWho/m;  # doesn't match, "Who" is not at start of string
517
518     $x =~ /girl$/m;  # matches, "girl" at end of first line
519     $x =~ /girl\Z/m; # doesn't match, "girl" is not at end of string
520
521     $x =~ /Perl\Z/m; # matches, "Perl" is at newline before end
522     $x =~ /Perl\z/m; # doesn't match, "Perl" is not at end of string
523
524 We now know how to create choices among classes of characters in a
525 regexp.  What about choices among words or character strings? Such
526 choices are described in the next section.
527
528 =head2 Matching this or that
529
530 Sometimes we would like our regexp to be able to match different
531 possible words or character strings.  This is accomplished by using
532 the I<alternation> metacharacter C<|>.  To match C<dog> or C<cat>, we
533 form the regexp C<dog|cat>.  As before, Perl will try to match the
534 regexp at the earliest possible point in the string.  At each
535 character position, Perl will first try to match the first
536 alternative, C<dog>.  If C<dog> doesn't match, Perl will then try the
537 next alternative, C<cat>.  If C<cat> doesn't match either, then the
538 match fails and Perl moves to the next position in the string.  Some
539 examples:
540
541     "cats and dogs" =~ /cat|dog|bird/;  # matches "cat"
542     "cats and dogs" =~ /dog|cat|bird/;  # matches "cat"
543
544 Even though C<dog> is the first alternative in the second regexp,
545 C<cat> is able to match earlier in the string.
546
547     "cats"          =~ /c|ca|cat|cats/; # matches "c"
548     "cats"          =~ /cats|cat|ca|c/; # matches "cats"
549
550 Here, all the alternatives match at the first string position, so the
551 first alternative is the one that matches.  If some of the
552 alternatives are truncations of the others, put the longest ones first
553 to give them a chance to match.
554
555     "cab" =~ /a|b|c/ # matches "c"
556                      # /a|b|c/ == /[abc]/
557
558 The last example points out that character classes are like
559 alternations of characters.  At a given character position, the first
560 alternative that allows the regexp match to succeed will be the one
561 that matches.
562
563 =head2 Grouping things and hierarchical matching
564
565 Alternation allows a regexp to choose among alternatives, but by
566 itself it is unsatisfying.  The reason is that each alternative is a whole
567 regexp, but sometime we want alternatives for just part of a
568 regexp.  For instance, suppose we want to search for housecats or
569 housekeepers.  The regexp C<housecat|housekeeper> fits the bill, but is
570 inefficient because we had to type C<house> twice.  It would be nice to
571 have parts of the regexp be constant, like C<house>, and some
572 parts have alternatives, like C<cat|keeper>.
573
574 The I<grouping> metacharacters C<()> solve this problem.  Grouping
575 allows parts of a regexp to be treated as a single unit.  Parts of a
576 regexp are grouped by enclosing them in parentheses.  Thus we could solve
577 the C<housecat|housekeeper> by forming the regexp as
578 C<house(cat|keeper)>.  The regexp C<house(cat|keeper)> means match
579 C<house> followed by either C<cat> or C<keeper>.  Some more examples
580 are
581
582     /(a|b)b/;    # matches 'ab' or 'bb'
583     /(ac|b)b/;   # matches 'acb' or 'bb'
584     /(^a|b)c/;   # matches 'ac' at start of string or 'bc' anywhere
585     /(a|[bc])d/; # matches 'ad', 'bd', or 'cd'
586
587     /house(cat|)/;  # matches either 'housecat' or 'house'
588     /house(cat(s|)|)/;  # matches either 'housecats' or 'housecat' or
589                         # 'house'.  Note groups can be nested.
590
591     /(19|20|)\d\d/;  # match years 19xx, 20xx, or the Y2K problem, xx
592     "20" =~ /(19|20|)\d\d/;  # matches the null alternative '()\d\d',
593                              # because '20\d\d' can't match
594
595 Alternations behave the same way in groups as out of them: at a given
596 string position, the leftmost alternative that allows the regexp to
597 match is taken.  So in the last example at the first string position,
598 C<"20"> matches the second alternative, but there is nothing left over
599 to match the next two digits C<\d\d>.  So Perl moves on to the next
600 alternative, which is the null alternative and that works, since
601 C<"20"> is two digits.
602
603 The process of trying one alternative, seeing if it matches, and
604 moving on to the next alternative, while going back in the string
605 from where the previous alternative was tried, if it doesn't, is called
606 I<backtracking>.  The term 'backtracking' comes from the idea that
607 matching a regexp is like a walk in the woods.  Successfully matching
608 a regexp is like arriving at a destination.  There are many possible
609 trailheads, one for each string position, and each one is tried in
610 order, left to right.  From each trailhead there may be many paths,
611 some of which get you there, and some which are dead ends.  When you
612 walk along a trail and hit a dead end, you have to backtrack along the
613 trail to an earlier point to try another trail.  If you hit your
614 destination, you stop immediately and forget about trying all the
615 other trails.  You are persistent, and only if you have tried all the
616 trails from all the trailheads and not arrived at your destination, do
617 you declare failure.  To be concrete, here is a step-by-step analysis
618 of what Perl does when it tries to match the regexp
619
620     "abcde" =~ /(abd|abc)(df|d|de)/;
621
622 =over 4
623
624 =item 0
625
626 Start with the first letter in the string 'a'.
627
628 =item 1
629
630 Try the first alternative in the first group 'abd'.
631
632 =item 2
633
634 Match 'a' followed by 'b'. So far so good.
635
636 =item 3
637
638 'd' in the regexp doesn't match 'c' in the string - a dead
639 end.  So backtrack two characters and pick the second alternative in
640 the first group 'abc'.
641
642 =item 4
643
644 Match 'a' followed by 'b' followed by 'c'.  We are on a roll
645 and have satisfied the first group. Set $1 to 'abc'.
646
647 =item 5
648
649 Move on to the second group and pick the first alternative
650 'df'.
651
652 =item 6
653
654 Match the 'd'.
655
656 =item 7
657
658 'f' in the regexp doesn't match 'e' in the string, so a dead
659 end.  Backtrack one character and pick the second alternative in the
660 second group 'd'.
661
662 =item 8
663
664 'd' matches. The second grouping is satisfied, so set $2 to
665 'd'.
666
667 =item 9
668
669 We are at the end of the regexp, so we are done! We have
670 matched 'abcd' out of the string "abcde".
671
672 =back
673
674 There are a couple of things to note about this analysis.  First, the
675 third alternative in the second group 'de' also allows a match, but we
676 stopped before we got to it - at a given character position, leftmost
677 wins.  Second, we were able to get a match at the first character
678 position of the string 'a'.  If there were no matches at the first
679 position, Perl would move to the second character position 'b' and
680 attempt the match all over again.  Only when all possible paths at all
681 possible character positions have been exhausted does Perl give
682 up and declare S<C<$string =~ /(abd|abc)(df|d|de)/;>> to be false.
683
684 Even with all this work, regexp matching happens remarkably fast.  To
685 speed things up, Perl compiles the regexp into a compact sequence of
686 opcodes that can often fit inside a processor cache.  When the code is
687 executed, these opcodes can then run at full throttle and search very
688 quickly.
689
690 =head2 Extracting matches
691
692 The grouping metacharacters C<()> also serve another completely
693 different function: they allow the extraction of the parts of a string
694 that matched.  This is very useful to find out what matched and for
695 text processing in general.  For each grouping, the part that matched
696 inside goes into the special variables C<$1>, C<$2>, etc.  They can be
697 used just as ordinary variables:
698
699     # extract hours, minutes, seconds
700     if ($time =~ /(\d\d):(\d\d):(\d\d)/) {    # match hh:mm:ss format
701         $hours = $1;
702         $minutes = $2;
703         $seconds = $3;
704     }
705
706 Now, we know that in scalar context,
707 S<C<$time =~ /(\d\d):(\d\d):(\d\d)/>> returns a true or false
708 value.  In list context, however, it returns the list of matched values
709 C<($1,$2,$3)>.  So we could write the code more compactly as
710
711     # extract hours, minutes, seconds
712     ($hours, $minutes, $second) = ($time =~ /(\d\d):(\d\d):(\d\d)/);
713
714 If the groupings in a regexp are nested, C<$1> gets the group with the
715 leftmost opening parenthesis, C<$2> the next opening parenthesis,
716 etc.  Here is a regexp with nested groups:
717
718     /(ab(cd|ef)((gi)|j))/;
719      1  2      34
720
721 If this regexp matches, C<$1> contains a string starting with
722 C<'ab'>, C<$2> is either set to C<'cd'> or C<'ef'>, C<$3> equals either
723 C<'gi'> or C<'j'>, and C<$4> is either set to C<'gi'>, just like C<$3>,
724 or it remains undefined.
725
726 For convenience, Perl sets C<$+> to the string held by the highest numbered
727 C<$1>, C<$2>,... that got assigned (and, somewhat related, C<$^N> to the
728 value of the C<$1>, C<$2>,... most-recently assigned; i.e. the C<$1>,
729 C<$2>,... associated with the rightmost closing parenthesis used in the
730 match).
731
732
733 =head2 Backreferences
734
735 Closely associated with the matching variables C<$1>, C<$2>, ... are
736 the I<backreferences> C<\g1>, C<\g2>,...  Backreferences are simply
737 matching variables that can be used I<inside> a regexp.  This is a
738 really nice feature; what matches later in a regexp is made to depend on
739 what matched earlier in the regexp.  Suppose we wanted to look
740 for doubled words in a text, like 'the the'.  The following regexp finds
741 all 3-letter doubles with a space in between:
742
743     /\b(\w\w\w)\s\g1\b/;
744
745 The grouping assigns a value to \g1, so that the same 3 letter sequence
746 is used for both parts.
747
748 A similar task is to find words consisting of two identical parts:
749
750     % simple_grep '^(\w\w\w\w|\w\w\w|\w\w|\w)\g1$' /usr/dict/words
751     beriberi
752     booboo
753     coco
754     mama
755     murmur
756     papa
757
758 The regexp has a single grouping which considers 4-letter
759 combinations, then 3-letter combinations, etc., and uses C<\g1> to look for
760 a repeat.  Although C<$1> and C<\g1> represent the same thing, care should be
761 taken to use matched variables C<$1>, C<$2>,... only I<outside> a regexp
762 and backreferences C<\g1>, C<\g2>,... only I<inside> a regexp; not doing
763 so may lead to surprising and unsatisfactory results.
764
765
766 =head2 Relative backreferences
767
768 Counting the opening parentheses to get the correct number for a
769 backreference is errorprone as soon as there is more than one
770 capturing group.  A more convenient technique became available
771 with Perl 5.10: relative backreferences. To refer to the immediately
772 preceding capture group one now may write C<\g{-1}>, the next but
773 last is available via C<\g{-2}>, and so on.
774
775 Another good reason in addition to readability and maintainability
776 for using relative backreferences  is illustrated by the following example,
777 where a simple pattern for matching peculiar strings is used:
778
779     $a99a = '([a-z])(\d)\g2\g1';   # matches a11a, g22g, x33x, etc.
780
781 Now that we have this pattern stored as a handy string, we might feel
782 tempted to use it as a part of some other pattern:
783
784     $line = "code=e99e";
785     if ($line =~ /^(\w+)=$a99a$/){   # unexpected behavior!
786         print "$1 is valid\n";
787     } else {
788         print "bad line: '$line'\n";
789     }
790
791 But this doesn't match, at least not the way one might expect. Only
792 after inserting the interpolated C<$a99a> and looking at the resulting
793 full text of the regexp is it obvious that the backreferences have
794 backfired. The subexpression C<(\w+)> has snatched number 1 and
795 demoted the groups in C<$a99a> by one rank. This can be avoided by
796 using relative backreferences:
797
798     $a99a = '([a-z])(\d)\g{-1}\g{-2}';  # safe for being interpolated
799
800
801 =head2 Named backreferences
802
803 Perl 5.10 also introduced named capture groups and named backreferences.
804 To attach a name to a capturing group, you write either
805 C<< (?<name>...) >> or C<< (?'name'...) >>.  The backreference may
806 then be written as C<\g{name}>.  It is permissible to attach the
807 same name to more than one group, but then only the leftmost one of the
808 eponymous set can be referenced.  Outside of the pattern a named
809 capture group is accessible through the C<%+> hash.
810
811 Assuming that we have to match calendar dates which may be given in one
812 of the three formats yyyy-mm-dd, mm/dd/yyyy or dd.mm.yyyy, we can write
813 three suitable patterns where we use 'd', 'm' and 'y' respectively as the
814 names of the groups capturing the pertaining components of a date. The
815 matching operation combines the three patterns as alternatives:
816
817     $fmt1 = '(?<y>\d\d\d\d)-(?<m>\d\d)-(?<d>\d\d)';
818     $fmt2 = '(?<m>\d\d)/(?<d>\d\d)/(?<y>\d\d\d\d)';
819     $fmt3 = '(?<d>\d\d)\.(?<m>\d\d)\.(?<y>\d\d\d\d)';
820     for my $d qw( 2006-10-21 15.01.2007 10/31/2005 ){
821         if ( $d =~ m{$fmt1|$fmt2|$fmt3} ){
822             print "day=$+{d} month=$+{m} year=$+{y}\n";
823         }
824     }
825
826 If any of the alternatives matches, the hash C<%+> is bound to contain the
827 three key-value pairs.
828
829
830 =head2 Alternative capture group numbering
831
832 Yet another capturing group numbering technique (also as from Perl 5.10)
833 deals with the problem of referring to groups within a set of alternatives.
834 Consider a pattern for matching a time of the day, civil or military style:
835
836     if ( $time =~ /(\d\d|\d):(\d\d)|(\d\d)(\d\d)/ ){
837         # process hour and minute
838     }
839
840 Processing the results requires an additional if statement to determine
841 whether C<$1> and C<$2> or C<$3> and C<$4> contain the goodies. It would
842 be easier if we could use group numbers 1 and 2 in second alternative as
843 well, and this is exactly what the parenthesized construct C<(?|...)>,
844 set around an alternative achieves. Here is an extended version of the
845 previous pattern:
846
847     if ( $time =~ /(?|(\d\d|\d):(\d\d)|(\d\d)(\d\d))\s+([A-Z][A-Z][A-Z])/ ){
848         print "hour=$1 minute=$2 zone=$3\n";
849     }
850
851 Within the alternative numbering group, group numbers start at the same
852 position for each alternative. After the group, numbering continues
853 with one higher than the maximum reached across all the alternatives.
854
855 =head2 Position information
856
857 In addition to what was matched, Perl (since 5.6.0) also provides the
858 positions of what was matched as contents of the C<@-> and C<@+>
859 arrays. C<$-[0]> is the position of the start of the entire match and
860 C<$+[0]> is the position of the end. Similarly, C<$-[n]> is the
861 position of the start of the C<$n> match and C<$+[n]> is the position
862 of the end. If C<$n> is undefined, so are C<$-[n]> and C<$+[n]>. Then
863 this code
864
865     $x = "Mmm...donut, thought Homer";
866     $x =~ /^(Mmm|Yech)\.\.\.(donut|peas)/; # matches
867     foreach $expr (1..$#-) {
868         print "Match $expr: '${$expr}' at position ($-[$expr],$+[$expr])\n";
869     }
870
871 prints
872
873     Match 1: 'Mmm' at position (0,3)
874     Match 2: 'donut' at position (6,11)
875
876 Even if there are no groupings in a regexp, it is still possible to
877 find out what exactly matched in a string.  If you use them, Perl
878 will set C<$`> to the part of the string before the match, will set C<$&>
879 to the part of the string that matched, and will set C<$'> to the part
880 of the string after the match.  An example:
881
882     $x = "the cat caught the mouse";
883     $x =~ /cat/;  # $` = 'the ', $& = 'cat', $' = ' caught the mouse'
884     $x =~ /the/;  # $` = '', $& = 'the', $' = ' cat caught the mouse'
885
886 In the second match, C<$`> equals C<''> because the regexp matched at the
887 first character position in the string and stopped; it never saw the
888 second 'the'.  It is important to note that using C<$`> and C<$'>
889 slows down regexp matching quite a bit, while C<$&> slows it down to a
890 lesser extent, because if they are used in one regexp in a program,
891 they are generated for I<all> regexps in the program.  So if raw
892 performance is a goal of your application, they should be avoided.
893 If you need to extract the corresponding substrings, use C<@-> and
894 C<@+> instead:
895
896     $` is the same as substr( $x, 0, $-[0] )
897     $& is the same as substr( $x, $-[0], $+[0]-$-[0] )
898     $' is the same as substr( $x, $+[0] )
899
900
901 =head2 Non-capturing groupings
902
903 A group that is required to bundle a set of alternatives may or may not be
904 useful as a capturing group.  If it isn't, it just creates a superfluous
905 addition to the set of available capture group values, inside as well as
906 outside the regexp.  Non-capturing groupings, denoted by C<(?:regexp)>,
907 still allow the regexp to be treated as a single unit, but don't establish
908 a capturing group at the same time.  Both capturing and non-capturing
909 groupings are allowed to co-exist in the same regexp.  Because there is
910 no extraction, non-capturing groupings are faster than capturing
911 groupings.  Non-capturing groupings are also handy for choosing exactly
912 which parts of a regexp are to be extracted to matching variables:
913
914     # match a number, $1-$4 are set, but we only want $1
915     /([+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)/;
916
917     # match a number faster , only $1 is set
918     /([+-]?\ *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)/;
919
920     # match a number, get $1 = whole number, $2 = exponent
921     /([+-]?\ *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE]([+-]?\d+))?)/;
922
923 Non-capturing groupings are also useful for removing nuisance
924 elements gathered from a split operation where parentheses are
925 required for some reason:
926
927     $x = '12aba34ba5';
928     @num = split /(a|b)+/, $x;    # @num = ('12','a','34','a','5')
929     @num = split /(?:a|b)+/, $x;  # @num = ('12','34','5')
930
931
932 =head2 Matching repetitions
933
934 The examples in the previous section display an annoying weakness.  We
935 were only matching 3-letter words, or chunks of words of 4 letters or
936 less.  We'd like to be able to match words or, more generally, strings
937 of any length, without writing out tedious alternatives like
938 C<\w\w\w\w|\w\w\w|\w\w|\w>.
939
940 This is exactly the problem the I<quantifier> metacharacters C<?>,
941 C<*>, C<+>, and C<{}> were created for.  They allow us to delimit the
942 number of repeats for a portion of a regexp we consider to be a
943 match.  Quantifiers are put immediately after the character, character
944 class, or grouping that we want to specify.  They have the following
945 meanings:
946
947 =over 4
948
949 =item *
950
951 C<a?> means: match 'a' 1 or 0 times
952
953 =item *
954
955 C<a*> means: match 'a' 0 or more times, i.e., any number of times
956
957 =item *
958
959 C<a+> means: match 'a' 1 or more times, i.e., at least once
960
961 =item *
962
963 C<a{n,m}> means: match at least C<n> times, but not more than C<m>
964 times.
965
966 =item *
967
968 C<a{n,}> means: match at least C<n> or more times
969
970 =item *
971
972 C<a{n}> means: match exactly C<n> times
973
974 =back
975
976 Here are some examples:
977
978     /[a-z]+\s+\d*/;  # match a lowercase word, at least one space, and
979                      # any number of digits
980     /(\w+)\s+\g1/;    # match doubled words of arbitrary length
981     /y(es)?/i;       # matches 'y', 'Y', or a case-insensitive 'yes'
982     $year =~ /\d{2,4}/;  # make sure year is at least 2 but not more
983                          # than 4 digits
984     $year =~ /\d{4}|\d{2}/;    # better match; throw out 3 digit dates
985     $year =~ /\d{2}(\d{2})?/;  # same thing written differently. However,
986                                # this produces $1 and the other does not.
987
988     % simple_grep '^(\w+)\g1$' /usr/dict/words   # isn't this easier?
989     beriberi
990     booboo
991     coco
992     mama
993     murmur
994     papa
995
996 For all of these quantifiers, Perl will try to match as much of the
997 string as possible, while still allowing the regexp to succeed.  Thus
998 with C</a?.../>, Perl will first try to match the regexp with the C<a>
999 present; if that fails, Perl will try to match the regexp without the
1000 C<a> present.  For the quantifier C<*>, we get the following:
1001
1002     $x = "the cat in the hat";
1003     $x =~ /^(.*)(cat)(.*)$/; # matches,
1004                              # $1 = 'the '
1005                              # $2 = 'cat'
1006                              # $3 = ' in the hat'
1007
1008 Which is what we might expect, the match finds the only C<cat> in the
1009 string and locks onto it.  Consider, however, this regexp:
1010
1011     $x =~ /^(.*)(at)(.*)$/; # matches,
1012                             # $1 = 'the cat in the h'
1013                             # $2 = 'at'
1014                             # $3 = ''   (0 characters match)
1015
1016 One might initially guess that Perl would find the C<at> in C<cat> and
1017 stop there, but that wouldn't give the longest possible string to the
1018 first quantifier C<.*>.  Instead, the first quantifier C<.*> grabs as
1019 much of the string as possible while still having the regexp match.  In
1020 this example, that means having the C<at> sequence with the final C<at>
1021 in the string.  The other important principle illustrated here is that
1022 when there are two or more elements in a regexp, the I<leftmost>
1023 quantifier, if there is one, gets to grab as much the string as
1024 possible, leaving the rest of the regexp to fight over scraps.  Thus in
1025 our example, the first quantifier C<.*> grabs most of the string, while
1026 the second quantifier C<.*> gets the empty string.   Quantifiers that
1027 grab as much of the string as possible are called I<maximal match> or
1028 I<greedy> quantifiers.
1029
1030 When a regexp can match a string in several different ways, we can use
1031 the principles above to predict which way the regexp will match:
1032
1033 =over 4
1034
1035 =item *
1036
1037 Principle 0: Taken as a whole, any regexp will be matched at the
1038 earliest possible position in the string.
1039
1040 =item *
1041
1042 Principle 1: In an alternation C<a|b|c...>, the leftmost alternative
1043 that allows a match for the whole regexp will be the one used.
1044
1045 =item *
1046
1047 Principle 2: The maximal matching quantifiers C<?>, C<*>, C<+> and
1048 C<{n,m}> will in general match as much of the string as possible while
1049 still allowing the whole regexp to match.
1050
1051 =item *
1052
1053 Principle 3: If there are two or more elements in a regexp, the
1054 leftmost greedy quantifier, if any, will match as much of the string
1055 as possible while still allowing the whole regexp to match.  The next
1056 leftmost greedy quantifier, if any, will try to match as much of the
1057 string remaining available to it as possible, while still allowing the
1058 whole regexp to match.  And so on, until all the regexp elements are
1059 satisfied.
1060
1061 =back
1062
1063 As we have seen above, Principle 0 overrides the others. The regexp
1064 will be matched as early as possible, with the other principles
1065 determining how the regexp matches at that earliest character
1066 position.
1067
1068 Here is an example of these principles in action:
1069
1070     $x = "The programming republic of Perl";
1071     $x =~ /^(.+)(e|r)(.*)$/;  # matches,
1072                               # $1 = 'The programming republic of Pe'
1073                               # $2 = 'r'
1074                               # $3 = 'l'
1075
1076 This regexp matches at the earliest string position, C<'T'>.  One
1077 might think that C<e>, being leftmost in the alternation, would be
1078 matched, but C<r> produces the longest string in the first quantifier.
1079
1080     $x =~ /(m{1,2})(.*)$/;  # matches,
1081                             # $1 = 'mm'
1082                             # $2 = 'ing republic of Perl'
1083
1084 Here, The earliest possible match is at the first C<'m'> in
1085 C<programming>. C<m{1,2}> is the first quantifier, so it gets to match
1086 a maximal C<mm>.
1087
1088     $x =~ /.*(m{1,2})(.*)$/;  # matches,
1089                               # $1 = 'm'
1090                               # $2 = 'ing republic of Perl'
1091
1092 Here, the regexp matches at the start of the string. The first
1093 quantifier C<.*> grabs as much as possible, leaving just a single
1094 C<'m'> for the second quantifier C<m{1,2}>.
1095
1096     $x =~ /(.?)(m{1,2})(.*)$/;  # matches,
1097                                 # $1 = 'a'
1098                                 # $2 = 'mm'
1099                                 # $3 = 'ing republic of Perl'
1100
1101 Here, C<.?> eats its maximal one character at the earliest possible
1102 position in the string, C<'a'> in C<programming>, leaving C<m{1,2}>
1103 the opportunity to match both C<m>'s. Finally,
1104
1105     "aXXXb" =~ /(X*)/; # matches with $1 = ''
1106
1107 because it can match zero copies of C<'X'> at the beginning of the
1108 string.  If you definitely want to match at least one C<'X'>, use
1109 C<X+>, not C<X*>.
1110
1111 Sometimes greed is not good.  At times, we would like quantifiers to
1112 match a I<minimal> piece of string, rather than a maximal piece.  For
1113 this purpose, Larry Wall created the I<minimal match> or
1114 I<non-greedy> quantifiers C<??>, C<*?>, C<+?>, and C<{}?>.  These are
1115 the usual quantifiers with a C<?> appended to them.  They have the
1116 following meanings:
1117
1118 =over 4
1119
1120 =item *
1121
1122 C<a??> means: match 'a' 0 or 1 times. Try 0 first, then 1.
1123
1124 =item *
1125
1126 C<a*?> means: match 'a' 0 or more times, i.e., any number of times,
1127 but as few times as possible
1128
1129 =item *
1130
1131 C<a+?> means: match 'a' 1 or more times, i.e., at least once, but
1132 as few times as possible
1133
1134 =item *
1135
1136 C<a{n,m}?> means: match at least C<n> times, not more than C<m>
1137 times, as few times as possible
1138
1139 =item *
1140
1141 C<a{n,}?> means: match at least C<n> times, but as few times as
1142 possible
1143
1144 =item *
1145
1146 C<a{n}?> means: match exactly C<n> times.  Because we match exactly
1147 C<n> times, C<a{n}?> is equivalent to C<a{n}> and is just there for
1148 notational consistency.
1149
1150 =back
1151
1152 Let's look at the example above, but with minimal quantifiers:
1153
1154     $x = "The programming republic of Perl";
1155     $x =~ /^(.+?)(e|r)(.*)$/; # matches,
1156                               # $1 = 'Th'
1157                               # $2 = 'e'
1158                               # $3 = ' programming republic of Perl'
1159
1160 The minimal string that will allow both the start of the string C<^>
1161 and the alternation to match is C<Th>, with the alternation C<e|r>
1162 matching C<e>.  The second quantifier C<.*> is free to gobble up the
1163 rest of the string.
1164
1165     $x =~ /(m{1,2}?)(.*?)$/;  # matches,
1166                               # $1 = 'm'
1167                               # $2 = 'ming republic of Perl'
1168
1169 The first string position that this regexp can match is at the first
1170 C<'m'> in C<programming>. At this position, the minimal C<m{1,2}?>
1171 matches just one C<'m'>.  Although the second quantifier C<.*?> would
1172 prefer to match no characters, it is constrained by the end-of-string
1173 anchor C<$> to match the rest of the string.
1174
1175     $x =~ /(.*?)(m{1,2}?)(.*)$/;  # matches,
1176                                   # $1 = 'The progra'
1177                                   # $2 = 'm'
1178                                   # $3 = 'ming republic of Perl'
1179
1180 In this regexp, you might expect the first minimal quantifier C<.*?>
1181 to match the empty string, because it is not constrained by a C<^>
1182 anchor to match the beginning of the word.  Principle 0 applies here,
1183 however.  Because it is possible for the whole regexp to match at the
1184 start of the string, it I<will> match at the start of the string.  Thus
1185 the first quantifier has to match everything up to the first C<m>.  The
1186 second minimal quantifier matches just one C<m> and the third
1187 quantifier matches the rest of the string.
1188
1189     $x =~ /(.??)(m{1,2})(.*)$/;  # matches,
1190                                  # $1 = 'a'
1191                                  # $2 = 'mm'
1192                                  # $3 = 'ing republic of Perl'
1193
1194 Just as in the previous regexp, the first quantifier C<.??> can match
1195 earliest at position C<'a'>, so it does.  The second quantifier is
1196 greedy, so it matches C<mm>, and the third matches the rest of the
1197 string.
1198
1199 We can modify principle 3 above to take into account non-greedy
1200 quantifiers:
1201
1202 =over 4
1203
1204 =item *
1205
1206 Principle 3: If there are two or more elements in a regexp, the
1207 leftmost greedy (non-greedy) quantifier, if any, will match as much
1208 (little) of the string as possible while still allowing the whole
1209 regexp to match.  The next leftmost greedy (non-greedy) quantifier, if
1210 any, will try to match as much (little) of the string remaining
1211 available to it as possible, while still allowing the whole regexp to
1212 match.  And so on, until all the regexp elements are satisfied.
1213
1214 =back
1215
1216 Just like alternation, quantifiers are also susceptible to
1217 backtracking.  Here is a step-by-step analysis of the example
1218
1219     $x = "the cat in the hat";
1220     $x =~ /^(.*)(at)(.*)$/; # matches,
1221                             # $1 = 'the cat in the h'
1222                             # $2 = 'at'
1223                             # $3 = ''   (0 matches)
1224
1225 =over 4
1226
1227 =item 0
1228
1229 Start with the first letter in the string 't'.
1230
1231 =item 1
1232
1233 The first quantifier '.*' starts out by matching the whole
1234 string 'the cat in the hat'.
1235
1236 =item 2
1237
1238 'a' in the regexp element 'at' doesn't match the end of the
1239 string.  Backtrack one character.
1240
1241 =item 3
1242
1243 'a' in the regexp element 'at' still doesn't match the last
1244 letter of the string 't', so backtrack one more character.
1245
1246 =item 4
1247
1248 Now we can match the 'a' and the 't'.
1249
1250 =item 5
1251
1252 Move on to the third element '.*'.  Since we are at the end of
1253 the string and '.*' can match 0 times, assign it the empty string.
1254
1255 =item 6
1256
1257 We are done!
1258
1259 =back
1260
1261 Most of the time, all this moving forward and backtracking happens
1262 quickly and searching is fast. There are some pathological regexps,
1263 however, whose execution time exponentially grows with the size of the
1264 string.  A typical structure that blows up in your face is of the form
1265
1266     /(a|b+)*/;
1267
1268 The problem is the nested indeterminate quantifiers.  There are many
1269 different ways of partitioning a string of length n between the C<+>
1270 and C<*>: one repetition with C<b+> of length n, two repetitions with
1271 the first C<b+> length k and the second with length n-k, m repetitions
1272 whose bits add up to length n, etc.  In fact there are an exponential
1273 number of ways to partition a string as a function of its length.  A
1274 regexp may get lucky and match early in the process, but if there is
1275 no match, Perl will try I<every> possibility before giving up.  So be
1276 careful with nested C<*>'s, C<{n,m}>'s, and C<+>'s.  The book
1277 I<Mastering Regular Expressions> by Jeffrey Friedl gives a wonderful
1278 discussion of this and other efficiency issues.
1279
1280
1281 =head2 Possessive quantifiers
1282
1283 Backtracking during the relentless search for a match may be a waste
1284 of time, particularly when the match is bound to fail.  Consider
1285 the simple pattern
1286
1287     /^\w+\s+\w+$/; # a word, spaces, a word
1288
1289 Whenever this is applied to a string which doesn't quite meet the
1290 pattern's expectations such as S<C<"abc  ">> or S<C<"abc  def ">>,
1291 the regex engine will backtrack, approximately once for each character
1292 in the string.  But we know that there is no way around taking I<all>
1293 of the initial word characters to match the first repetition, that I<all>
1294 spaces must be eaten by the middle part, and the same goes for the second
1295 word.
1296
1297 With the introduction of the I<possessive quantifiers> in Perl 5.10, we
1298 have a way of instructing the regex engine not to backtrack, with the
1299 usual quantifiers with a C<+> appended to them.  This makes them greedy as
1300 well as stingy; once they succeed they won't give anything back to permit
1301 another solution. They have the following meanings:
1302
1303 =over 4
1304
1305 =item *
1306
1307 C<a{n,m}+> means: match at least C<n> times, not more than C<m> times,
1308 as many times as possible, and don't give anything up. C<a?+> is short
1309 for C<a{0,1}+>
1310
1311 =item *
1312
1313 C<a{n,}+> means: match at least C<n> times, but as many times as possible,
1314 and don't give anything up. C<a*+> is short for C<a{0,}+> and C<a++> is
1315 short for C<a{1,}+>.
1316
1317 =item *
1318
1319 C<a{n}+> means: match exactly C<n> times.  It is just there for
1320 notational consistency.
1321
1322 =back
1323
1324 These possessive quantifiers represent a special case of a more general
1325 concept, the I<independent subexpression>, see below.
1326
1327 As an example where a possessive quantifier is suitable we consider
1328 matching a quoted string, as it appears in several programming languages.
1329 The backslash is used as an escape character that indicates that the
1330 next character is to be taken literally, as another character for the
1331 string.  Therefore, after the opening quote, we expect a (possibly
1332 empty) sequence of alternatives: either some character except an
1333 unescaped quote or backslash or an escaped character.
1334
1335     /"(?:[^"\\]++|\\.)*+"/;
1336
1337
1338 =head2 Building a regexp
1339
1340 At this point, we have all the basic regexp concepts covered, so let's
1341 give a more involved example of a regular expression.  We will build a
1342 regexp that matches numbers.
1343
1344 The first task in building a regexp is to decide what we want to match
1345 and what we want to exclude.  In our case, we want to match both
1346 integers and floating point numbers and we want to reject any string
1347 that isn't a number.
1348
1349 The next task is to break the problem down into smaller problems that
1350 are easily converted into a regexp.
1351
1352 The simplest case is integers.  These consist of a sequence of digits,
1353 with an optional sign in front.  The digits we can represent with
1354 C<\d+> and the sign can be matched with C<[+-]>.  Thus the integer
1355 regexp is
1356
1357     /[+-]?\d+/;  # matches integers
1358
1359 A floating point number potentially has a sign, an integral part, a
1360 decimal point, a fractional part, and an exponent.  One or more of these
1361 parts is optional, so we need to check out the different
1362 possibilities.  Floating point numbers which are in proper form include
1363 123., 0.345, .34, -1e6, and 25.4E-72.  As with integers, the sign out
1364 front is completely optional and can be matched by C<[+-]?>.  We can
1365 see that if there is no exponent, floating point numbers must have a
1366 decimal point, otherwise they are integers.  We might be tempted to
1367 model these with C<\d*\.\d*>, but this would also match just a single
1368 decimal point, which is not a number.  So the three cases of floating
1369 point number without exponent are
1370
1371    /[+-]?\d+\./;  # 1., 321., etc.
1372    /[+-]?\.\d+/;  # .1, .234, etc.
1373    /[+-]?\d+\.\d+/;  # 1.0, 30.56, etc.
1374
1375 These can be combined into a single regexp with a three-way alternation:
1376
1377    /[+-]?(\d+\.\d+|\d+\.|\.\d+)/;  # floating point, no exponent
1378
1379 In this alternation, it is important to put C<'\d+\.\d+'> before
1380 C<'\d+\.'>.  If C<'\d+\.'> were first, the regexp would happily match that
1381 and ignore the fractional part of the number.
1382
1383 Now consider floating point numbers with exponents.  The key
1384 observation here is that I<both> integers and numbers with decimal
1385 points are allowed in front of an exponent.  Then exponents, like the
1386 overall sign, are independent of whether we are matching numbers with
1387 or without decimal points, and can be 'decoupled' from the
1388 mantissa.  The overall form of the regexp now becomes clear:
1389
1390     /^(optional sign)(integer | f.p. mantissa)(optional exponent)$/;
1391
1392 The exponent is an C<e> or C<E>, followed by an integer.  So the
1393 exponent regexp is
1394
1395    /[eE][+-]?\d+/;  # exponent
1396
1397 Putting all the parts together, we get a regexp that matches numbers:
1398
1399    /^[+-]?(\d+\.\d+|\d+\.|\.\d+|\d+)([eE][+-]?\d+)?$/;  # Ta da!
1400
1401 Long regexps like this may impress your friends, but can be hard to
1402 decipher.  In complex situations like this, the C<//x> modifier for a
1403 match is invaluable.  It allows one to put nearly arbitrary whitespace
1404 and comments into a regexp without affecting their meaning.  Using it,
1405 we can rewrite our 'extended' regexp in the more pleasing form
1406
1407    /^
1408       [+-]?         # first, match an optional sign
1409       (             # then match integers or f.p. mantissas:
1410           \d+\.\d+  # mantissa of the form a.b
1411          |\d+\.     # mantissa of the form a.
1412          |\.\d+     # mantissa of the form .b
1413          |\d+       # integer of the form a
1414       )
1415       ([eE][+-]?\d+)?  # finally, optionally match an exponent
1416    $/x;
1417
1418 If whitespace is mostly irrelevant, how does one include space
1419 characters in an extended regexp? The answer is to backslash it
1420 S<C<'\ '>> or put it in a character class S<C<[ ]>>.  The same thing
1421 goes for pound signs, use C<\#> or C<[#]>.  For instance, Perl allows
1422 a space between the sign and the mantissa or integer, and we could add
1423 this to our regexp as follows:
1424
1425    /^
1426       [+-]?\ *      # first, match an optional sign *and space*
1427       (             # then match integers or f.p. mantissas:
1428           \d+\.\d+  # mantissa of the form a.b
1429          |\d+\.     # mantissa of the form a.
1430          |\.\d+     # mantissa of the form .b
1431          |\d+       # integer of the form a
1432       )
1433       ([eE][+-]?\d+)?  # finally, optionally match an exponent
1434    $/x;
1435
1436 In this form, it is easier to see a way to simplify the
1437 alternation.  Alternatives 1, 2, and 4 all start with C<\d+>, so it
1438 could be factored out:
1439
1440    /^
1441       [+-]?\ *      # first, match an optional sign
1442       (             # then match integers or f.p. mantissas:
1443           \d+       # start out with a ...
1444           (
1445               \.\d* # mantissa of the form a.b or a.
1446           )?        # ? takes care of integers of the form a
1447          |\.\d+     # mantissa of the form .b
1448       )
1449       ([eE][+-]?\d+)?  # finally, optionally match an exponent
1450    $/x;
1451
1452 or written in the compact form,
1453
1454     /^[+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/;
1455
1456 This is our final regexp.  To recap, we built a regexp by
1457
1458 =over 4
1459
1460 =item *
1461
1462 specifying the task in detail,
1463
1464 =item *
1465
1466 breaking down the problem into smaller parts,
1467
1468 =item *
1469
1470 translating the small parts into regexps,
1471
1472 =item *
1473
1474 combining the regexps,
1475
1476 =item *
1477
1478 and optimizing the final combined regexp.
1479
1480 =back
1481
1482 These are also the typical steps involved in writing a computer
1483 program.  This makes perfect sense, because regular expressions are
1484 essentially programs written in a little computer language that specifies
1485 patterns.
1486
1487 =head2 Using regular expressions in Perl
1488
1489 The last topic of Part 1 briefly covers how regexps are used in Perl
1490 programs.  Where do they fit into Perl syntax?
1491
1492 We have already introduced the matching operator in its default
1493 C</regexp/> and arbitrary delimiter C<m!regexp!> forms.  We have used
1494 the binding operator C<=~> and its negation C<!~> to test for string
1495 matches.  Associated with the matching operator, we have discussed the
1496 single line C<//s>, multi-line C<//m>, case-insensitive C<//i> and
1497 extended C<//x> modifiers.  There are a few more things you might
1498 want to know about matching operators.
1499
1500 =head3 Optimizing pattern evaluation
1501
1502 We pointed out earlier that variables in regexps are substituted
1503 before the regexp is evaluated:
1504
1505     $pattern = 'Seuss';
1506     while (<>) {
1507         print if /$pattern/;
1508     }
1509
1510 This will print any lines containing the word C<Seuss>.  It is not as
1511 efficient as it could be, however, because Perl has to re-evaluate
1512 (or compile) C<$pattern> each time through the loop.  If C<$pattern> won't be
1513 changing over the lifetime of the script, we can add the C<//o>
1514 modifier, which directs Perl to only perform variable substitutions
1515 once:
1516
1517     #!/usr/bin/perl
1518     #    Improved simple_grep
1519     $regexp = shift;
1520     while (<>) {
1521         print if /$regexp/o;  # a good deal faster
1522     }
1523
1524
1525 =head3 Prohibiting substitution
1526
1527 If you change C<$pattern> after the first substitution happens, Perl
1528 will ignore it.  If you don't want any substitutions at all, use the
1529 special delimiter C<m''>:
1530
1531     @pattern = ('Seuss');
1532     while (<>) {
1533         print if m'@pattern';  # matches literal '@pattern', not 'Seuss'
1534     }
1535
1536 Similar to strings, C<m''> acts like apostrophes on a regexp; all other
1537 C<m> delimiters act like quotes.  If the regexp evaluates to the empty string,
1538 the regexp in the I<last successful match> is used instead.  So we have
1539
1540     "dog" =~ /d/;  # 'd' matches
1541     "dogbert =~ //;  # this matches the 'd' regexp used before
1542
1543
1544 =head3 Global matching
1545
1546 The final two modifiers C<//g> and C<//c> concern multiple matches.
1547 The modifier C<//g> stands for global matching and allows the
1548 matching operator to match within a string as many times as possible.
1549 In scalar context, successive invocations against a string will have
1550 `C<//g> jump from match to match, keeping track of position in the
1551 string as it goes along.  You can get or set the position with the
1552 C<pos()> function.
1553
1554 The use of C<//g> is shown in the following example.  Suppose we have
1555 a string that consists of words separated by spaces.  If we know how
1556 many words there are in advance, we could extract the words using
1557 groupings:
1558
1559     $x = "cat dog house"; # 3 words
1560     $x =~ /^\s*(\w+)\s+(\w+)\s+(\w+)\s*$/; # matches,
1561                                            # $1 = 'cat'
1562                                            # $2 = 'dog'
1563                                            # $3 = 'house'
1564
1565 But what if we had an indeterminate number of words? This is the sort
1566 of task C<//g> was made for.  To extract all words, form the simple
1567 regexp C<(\w+)> and loop over all matches with C</(\w+)/g>:
1568
1569     while ($x =~ /(\w+)/g) {
1570         print "Word is $1, ends at position ", pos $x, "\n";
1571     }
1572
1573 prints
1574
1575     Word is cat, ends at position 3
1576     Word is dog, ends at position 7
1577     Word is house, ends at position 13
1578
1579 A failed match or changing the target string resets the position.  If
1580 you don't want the position reset after failure to match, add the
1581 C<//c>, as in C</regexp/gc>.  The current position in the string is
1582 associated with the string, not the regexp.  This means that different
1583 strings have different positions and their respective positions can be
1584 set or read independently.
1585
1586 In list context, C<//g> returns a list of matched groupings, or if
1587 there are no groupings, a list of matches to the whole regexp.  So if
1588 we wanted just the words, we could use
1589
1590     @words = ($x =~ /(\w+)/g);  # matches,
1591                                 # $word[0] = 'cat'
1592                                 # $word[1] = 'dog'
1593                                 # $word[2] = 'house'
1594
1595 Closely associated with the C<//g> modifier is the C<\G> anchor.  The
1596 C<\G> anchor matches at the point where the previous C<//g> match left
1597 off.  C<\G> allows us to easily do context-sensitive matching:
1598
1599     $metric = 1;  # use metric units
1600     ...
1601     $x = <FILE>;  # read in measurement
1602     $x =~ /^([+-]?\d+)\s*/g;  # get magnitude
1603     $weight = $1;
1604     if ($metric) { # error checking
1605         print "Units error!" unless $x =~ /\Gkg\./g;
1606     }
1607     else {
1608         print "Units error!" unless $x =~ /\Glbs\./g;
1609     }
1610     $x =~ /\G\s+(widget|sprocket)/g;  # continue processing
1611
1612 The combination of C<//g> and C<\G> allows us to process the string a
1613 bit at a time and use arbitrary Perl logic to decide what to do next.
1614 Currently, the C<\G> anchor is only fully supported when used to anchor
1615 to the start of the pattern.
1616
1617 C<\G> is also invaluable in processing fixed length records with
1618 regexps.  Suppose we have a snippet of coding region DNA, encoded as
1619 base pair letters C<ATCGTTGAAT...> and we want to find all the stop
1620 codons C<TGA>.  In a coding region, codons are 3-letter sequences, so
1621 we can think of the DNA snippet as a sequence of 3-letter records.  The
1622 naive regexp
1623
1624     # expanded, this is "ATC GTT GAA TGC AAA TGA CAT GAC"
1625     $dna = "ATCGTTGAATGCAAATGACATGAC";
1626     $dna =~ /TGA/;
1627
1628 doesn't work; it may match a C<TGA>, but there is no guarantee that
1629 the match is aligned with codon boundaries, e.g., the substring
1630 S<C<GTT GAA>> gives a match.  A better solution is
1631
1632     while ($dna =~ /(\w\w\w)*?TGA/g) {  # note the minimal *?
1633         print "Got a TGA stop codon at position ", pos $dna, "\n";
1634     }
1635
1636 which prints
1637
1638     Got a TGA stop codon at position 18
1639     Got a TGA stop codon at position 23
1640
1641 Position 18 is good, but position 23 is bogus.  What happened?
1642
1643 The answer is that our regexp works well until we get past the last
1644 real match.  Then the regexp will fail to match a synchronized C<TGA>
1645 and start stepping ahead one character position at a time, not what we
1646 want.  The solution is to use C<\G> to anchor the match to the codon
1647 alignment:
1648
1649     while ($dna =~ /\G(\w\w\w)*?TGA/g) {
1650         print "Got a TGA stop codon at position ", pos $dna, "\n";
1651     }
1652
1653 This prints
1654
1655     Got a TGA stop codon at position 18
1656
1657 which is the correct answer.  This example illustrates that it is
1658 important not only to match what is desired, but to reject what is not
1659 desired.
1660
1661 =head3 Search and replace
1662
1663 Regular expressions also play a big role in I<search and replace>
1664 operations in Perl.  Search and replace is accomplished with the
1665 C<s///> operator.  The general form is
1666 C<s/regexp/replacement/modifiers>, with everything we know about
1667 regexps and modifiers applying in this case as well.  The
1668 C<replacement> is a Perl double quoted string that replaces in the
1669 string whatever is matched with the C<regexp>.  The operator C<=~> is
1670 also used here to associate a string with C<s///>.  If matching
1671 against C<$_>, the S<C<$_ =~>> can be dropped.  If there is a match,
1672 C<s///> returns the number of substitutions made, otherwise it returns
1673 false.  Here are a few examples:
1674
1675     $x = "Time to feed the cat!";
1676     $x =~ s/cat/hacker/;   # $x contains "Time to feed the hacker!"
1677     if ($x =~ s/^(Time.*hacker)!$/$1 now!/) {
1678         $more_insistent = 1;
1679     }
1680     $y = "'quoted words'";
1681     $y =~ s/^'(.*)'$/$1/;  # strip single quotes,
1682                            # $y contains "quoted words"
1683
1684 In the last example, the whole string was matched, but only the part
1685 inside the single quotes was grouped.  With the C<s///> operator, the
1686 matched variables C<$1>, C<$2>, etc.  are immediately available for use
1687 in the replacement expression, so we use C<$1> to replace the quoted
1688 string with just what was quoted.  With the global modifier, C<s///g>
1689 will search and replace all occurrences of the regexp in the string:
1690
1691     $x = "I batted 4 for 4";
1692     $x =~ s/4/four/;   # doesn't do it all:
1693                        # $x contains "I batted four for 4"
1694     $x = "I batted 4 for 4";
1695     $x =~ s/4/four/g;  # does it all:
1696                        # $x contains "I batted four for four"
1697
1698 If you prefer 'regex' over 'regexp' in this tutorial, you could use
1699 the following program to replace it:
1700
1701     % cat > simple_replace
1702     #!/usr/bin/perl
1703     $regexp = shift;
1704     $replacement = shift;
1705     while (<>) {
1706         s/$regexp/$replacement/go;
1707         print;
1708     }
1709     ^D
1710
1711     % simple_replace regexp regex perlretut.pod
1712
1713 In C<simple_replace> we used the C<s///g> modifier to replace all
1714 occurrences of the regexp on each line and the C<s///o> modifier to
1715 compile the regexp only once.  As with C<simple_grep>, both the
1716 C<print> and the C<s/$regexp/$replacement/go> use C<$_> implicitly.
1717
1718 If you don't want C<s///> to change your original variable you can use
1719 the non-destructive substitute modifier, C<s///r>.  This changes the
1720 behavior so that C<s///r> returns the final substituted string:
1721
1722     $x = "I like dogs.";
1723     $y = $x =~ s/dogs/cats/r;
1724     print "$x $y\n";
1725
1726 That example will print "I like dogs. I like cats". Notice the original
1727 C<$x> variable has not been affected by the substitute. The overall
1728 result of the substitution is instead stored in C<$y>. If the
1729 substitution doesn't affect anything then the original string is
1730 returned:
1731
1732     $x = "I like dogs.";
1733     $y = $x =~ s/elephants/cougars/r;
1734     print "$x $y\n"; # prints "I like dogs. I like dogs."
1735
1736 One other interesting thing that the C<s///r> flag allows is chaining
1737 substitutions:
1738
1739     $x = "Cats are great.";
1740     print $x =~ s/Cats/Dogs/r =~ s/Dogs/Frogs/r =~ s/Frogs/Hedgehogs/r, "\n";
1741     # prints "Hedgehogs are great."
1742
1743 A modifier available specifically to search and replace is the
1744 C<s///e> evaluation modifier.  C<s///e> wraps an C<eval{...}> around
1745 the replacement string and the evaluated result is substituted for the
1746 matched substring.  C<s///e> is useful if you need to do a bit of
1747 computation in the process of replacing text.  This example counts
1748 character frequencies in a line:
1749
1750     $x = "Bill the cat";
1751     $x =~ s/(.)/$chars{$1}++;$1/eg;  # final $1 replaces char with itself
1752     print "frequency of '$_' is $chars{$_}\n"
1753         foreach (sort {$chars{$b} <=> $chars{$a}} keys %chars);
1754
1755 This prints
1756
1757     frequency of ' ' is 2
1758     frequency of 't' is 2
1759     frequency of 'l' is 2
1760     frequency of 'B' is 1
1761     frequency of 'c' is 1
1762     frequency of 'e' is 1
1763     frequency of 'h' is 1
1764     frequency of 'i' is 1
1765     frequency of 'a' is 1
1766
1767 As with the match C<m//> operator, C<s///> can use other delimiters,
1768 such as C<s!!!> and C<s{}{}>, and even C<s{}//>.  If single quotes are
1769 used C<s'''>, then the regexp and replacement are treated as single
1770 quoted strings and there are no substitutions.  C<s///> in list context
1771 returns the same thing as in scalar context, i.e., the number of
1772 matches.
1773
1774 =head3 The split function
1775
1776 The C<split()> function is another place where a regexp is used.
1777 C<split /regexp/, string, limit> separates the C<string> operand into
1778 a list of substrings and returns that list.  The regexp must be designed
1779 to match whatever constitutes the separators for the desired substrings.
1780 The C<limit>, if present, constrains splitting into no more than C<limit>
1781 number of strings.  For example, to split a string into words, use
1782
1783     $x = "Calvin and Hobbes";
1784     @words = split /\s+/, $x;  # $word[0] = 'Calvin'
1785                                # $word[1] = 'and'
1786                                # $word[2] = 'Hobbes'
1787
1788 If the empty regexp C<//> is used, the regexp always matches and
1789 the string is split into individual characters.  If the regexp has
1790 groupings, then the resulting list contains the matched substrings from the
1791 groupings as well.  For instance,
1792
1793     $x = "/usr/bin/perl";
1794     @dirs = split m!/!, $x;  # $dirs[0] = ''
1795                              # $dirs[1] = 'usr'
1796                              # $dirs[2] = 'bin'
1797                              # $dirs[3] = 'perl'
1798     @parts = split m!(/)!, $x;  # $parts[0] = ''
1799                                 # $parts[1] = '/'
1800                                 # $parts[2] = 'usr'
1801                                 # $parts[3] = '/'
1802                                 # $parts[4] = 'bin'
1803                                 # $parts[5] = '/'
1804                                 # $parts[6] = 'perl'
1805
1806 Since the first character of $x matched the regexp, C<split> prepended
1807 an empty initial element to the list.
1808
1809 If you have read this far, congratulations! You now have all the basic
1810 tools needed to use regular expressions to solve a wide range of text
1811 processing problems.  If this is your first time through the tutorial,
1812 why not stop here and play around with regexps a while...  S<Part 2>
1813 concerns the more esoteric aspects of regular expressions and those
1814 concepts certainly aren't needed right at the start.
1815
1816 =head1 Part 2: Power tools
1817
1818 OK, you know the basics of regexps and you want to know more.  If
1819 matching regular expressions is analogous to a walk in the woods, then
1820 the tools discussed in Part 1 are analogous to topo maps and a
1821 compass, basic tools we use all the time.  Most of the tools in part 2
1822 are analogous to flare guns and satellite phones.  They aren't used
1823 too often on a hike, but when we are stuck, they can be invaluable.
1824
1825 What follows are the more advanced, less used, or sometimes esoteric
1826 capabilities of Perl regexps.  In Part 2, we will assume you are
1827 comfortable with the basics and concentrate on the new features.
1828
1829 =head2 More on characters, strings, and character classes
1830
1831 There are a number of escape sequences and character classes that we
1832 haven't covered yet.
1833
1834 There are several escape sequences that convert characters or strings
1835 between upper and lower case, and they are also available within
1836 patterns.  C<\l> and C<\u> convert the next character to lower or
1837 upper case, respectively:
1838
1839     $x = "perl";
1840     $string =~ /\u$x/;  # matches 'Perl' in $string
1841     $x = "M(rs?|s)\\."; # note the double backslash
1842     $string =~ /\l$x/;  # matches 'mr.', 'mrs.', and 'ms.',
1843
1844 A C<\L> or C<\U> indicates a lasting conversion of case, until
1845 terminated by C<\E> or thrown over by another C<\U> or C<\L>:
1846
1847     $x = "This word is in lower case:\L SHOUT\E";
1848     $x =~ /shout/;       # matches
1849     $x = "I STILL KEYPUNCH CARDS FOR MY 360"
1850     $x =~ /\Ukeypunch/;  # matches punch card string
1851
1852 If there is no C<\E>, case is converted until the end of the
1853 string. The regexps C<\L\u$word> or C<\u\L$word> convert the first
1854 character of C<$word> to uppercase and the rest of the characters to
1855 lowercase.
1856
1857 Control characters can be escaped with C<\c>, so that a control-Z
1858 character would be matched with C<\cZ>.  The escape sequence
1859 C<\Q>...C<\E> quotes, or protects most non-alphabetic characters.   For
1860 instance,
1861
1862     $x = "\QThat !^*&%~& cat!";
1863     $x =~ /\Q!^*&%~&\E/;  # check for rough language
1864
1865 It does not protect C<$> or C<@>, so that variables can still be
1866 substituted.
1867
1868 With the advent of 5.6.0, Perl regexps can handle more than just the
1869 standard ASCII character set.  Perl now supports I<Unicode>, a standard
1870 for representing the alphabets from virtually all of the world's written
1871 languages, and a host of symbols.  Perl's text strings are Unicode strings, so
1872 they can contain characters with a value (codepoint or character number) higher
1873 than 255
1874
1875 What does this mean for regexps? Well, regexp users don't need to know
1876 much about Perl's internal representation of strings.  But they do need
1877 to know 1) how to represent Unicode characters in a regexp and 2) that
1878 a matching operation will treat the string to be searched as a sequence
1879 of characters, not bytes.  The answer to 1) is that Unicode characters
1880 greater than C<chr(255)> are represented using the C<\x{hex}> notation, because
1881 \x hex (without curly braces) doesn't go further than 255.  (Starting in Perl
1882 5.14) if you're an octal fan, you can also use C<\o{oct}>.
1883
1884     /\x{263a}/;  # match a Unicode smiley face :)
1885
1886 B<NOTE>: In Perl 5.6.0 it used to be that one needed to say C<use
1887 utf8> to use any Unicode features.  This is no more the case: for
1888 almost all Unicode processing, the explicit C<utf8> pragma is not
1889 needed.  (The only case where it matters is if your Perl script is in
1890 Unicode and encoded in UTF-8, then an explicit C<use utf8> is needed.)
1891
1892 Figuring out the hexadecimal sequence of a Unicode character you want
1893 or deciphering someone else's hexadecimal Unicode regexp is about as
1894 much fun as programming in machine code.  So another way to specify
1895 Unicode characters is to use the I<named character> escape
1896 sequence C<\N{I<name>}>.  I<name> is a name for the Unicode character, as
1897 specified in the Unicode standard.  For instance, if we wanted to
1898 represent or match the astrological sign for the planet Mercury, we
1899 could use
1900
1901     use charnames ":full"; # use named chars with Unicode full names
1902     $x = "abc\N{MERCURY}def";
1903     $x =~ /\N{MERCURY}/;   # matches
1904
1905 One can also use short names or restrict names to a certain alphabet:
1906
1907     use charnames ':full';
1908     print "\N{GREEK SMALL LETTER SIGMA} is called sigma.\n";
1909
1910     use charnames ":short";
1911     print "\N{greek:Sigma} is an upper-case sigma.\n";
1912
1913     use charnames qw(greek);
1914     print "\N{sigma} is Greek sigma\n";
1915
1916 A list of full names is found in the file NamesList.txt in the
1917 lib/perl5/X.X.X/unicore directory (where X.X.X is the perl
1918 version number as it is installed on your system).
1919
1920 The answer to requirement 2), as of 5.6.0, is that a regexp uses Unicode
1921 characters. Internally, this is encoded to bytes using either UTF-8 or a
1922 native 8 bit encoding, depending on the history of the string, but
1923 conceptually it is a sequence of characters, not bytes. See
1924 L<perlunitut> for a tutorial about that.
1925
1926 Let us now discuss Unicode character classes.  Just as with Unicode
1927 characters, there are named Unicode character classes represented by the
1928 C<\p{name}> escape sequence.  Closely associated is the C<\P{name}>
1929 character class, which is the negation of the C<\p{name}> class.  For
1930 example, to match lower and uppercase characters,
1931
1932     use charnames ":full"; # use named chars with Unicode full names
1933     $x = "BOB";
1934     $x =~ /^\p{IsUpper}/;   # matches, uppercase char class
1935     $x =~ /^\P{IsUpper}/;   # doesn't match, char class sans uppercase
1936     $x =~ /^\p{IsLower}/;   # doesn't match, lowercase char class
1937     $x =~ /^\P{IsLower}/;   # matches, char class sans lowercase
1938
1939 Here is the association between some Perl named classes and the
1940 traditional Unicode classes:
1941
1942     Perl class name  Unicode class name or regular expression
1943
1944     IsAlpha          /^[LM]/
1945     IsAlnum          /^[LMN]/
1946     IsASCII          $code <= 127
1947     IsCntrl          /^C/
1948     IsBlank          $code =~ /^(0020|0009)$/ || /^Z[^lp]/
1949     IsDigit          Nd
1950     IsGraph          /^([LMNPS]|Co)/
1951     IsLower          Ll
1952     IsPrint          /^([LMNPS]|Co|Zs)/
1953     IsPunct          /^P/
1954     IsSpace          /^Z/ || ($code =~ /^(0009|000A|000B|000C|000D)$/
1955     IsSpacePerl      /^Z/ || ($code =~ /^(0009|000A|000C|000D|0085|2028|2029)$/
1956     IsUpper          /^L[ut]/
1957     IsWord           /^[LMN]/ || $code eq "005F"
1958     IsXDigit         $code =~ /^00(3[0-9]|[46][1-6])$/
1959
1960 You can also use the official Unicode class names with the C<\p> and
1961 C<\P>, like C<\p{L}> for Unicode 'letters', or C<\p{Lu}> for uppercase
1962 letters, or C<\P{Nd}> for non-digits.  If a C<name> is just one
1963 letter, the braces can be dropped.  For instance, C<\pM> is the
1964 character class of Unicode 'marks', for example accent marks.
1965 For the full list see L<perlunicode>.
1966
1967 The Unicode has also been separated into various sets of characters
1968 which you can test with C<\p{...}> (in) and C<\P{...}> (not in).
1969 To test whether a character is (or is not) an element of a script
1970 you would use the script name, for example C<\p{Latin}>, C<\p{Greek}>,
1971 or C<\P{Katakana}>. Other sets are the Unicode blocks, the names
1972 of which begin with "In". One such block is dedicated to mathematical
1973 operators, and its pattern formula is <C\p{InMathematicalOperators>}>.
1974 For the full list see L<perluniprops>.
1975
1976 What we have described so far is the single form of the C<\p{...}> character
1977 classes.  There is also a compound form which you may run into.  These
1978 look like C<\p{name=value}> or C<\p{name:value}> (the equals sign and colon
1979 can be used interchangeably).  These are more general than the single form,
1980 and in fact most of the single forms are just Perl-defined shortcuts for common
1981 compound forms.  For example, the script examples in the previous paragraph
1982 could be written equivalently as C<\p{Script=Latin}>, C<\p{Script:Greek}>, and
1983 C<\P{script=katakana}> (case is irrelevant between the C<{}> braces).  You may
1984 never have to use the compound forms, but sometimes it is necessary, and their
1985 use can make your code easier to understand.
1986
1987 C<\X> is an abbreviation for a character class that comprises
1988 a Unicode I<extended grapheme cluster>.  This represents a "logical character",
1989 what appears to be a single character, but may be represented internally by more
1990 than one.  As an example, using the Unicode full names, e.g., S<C<A + COMBINING
1991 RING>> is a grapheme cluster with base character C<A> and combining character
1992 S<C<COMBINING RING>>, which translates in Danish to A with the circle atop it,
1993 as in the word Angstrom.
1994
1995 For the full and latest information about Unicode see the latest
1996 Unicode standard, or the Unicode Consortium's website L<http://www.unicode.org>
1997
1998 As if all those classes weren't enough, Perl also defines POSIX style
1999 character classes.  These have the form C<[:name:]>, with C<name> the
2000 name of the POSIX class.  The POSIX classes are C<alpha>, C<alnum>,
2001 C<ascii>, C<cntrl>, C<digit>, C<graph>, C<lower>, C<print>, C<punct>,
2002 C<space>, C<upper>, and C<xdigit>, and two extensions, C<word> (a Perl
2003 extension to match C<\w>), and C<blank> (a GNU extension).  If C<utf8>
2004 is being used, then these classes are defined the same as their
2005 corresponding Perl Unicode classes: C<[:upper:]> is the same as
2006 C<\p{IsUpper}>, etc.  The POSIX character classes, however, don't
2007 require using C<utf8>.  The C<[:digit:]>, C<[:word:]>, and
2008 C<[:space:]> correspond to the familiar C<\d>, C<\w>, and C<\s>
2009 character classes.  To negate a POSIX class, put a C<^> in front of
2010 the name, so that, e.g., C<[:^digit:]> corresponds to C<\D> and under
2011 C<utf8>, C<\P{IsDigit}>.  The Unicode and POSIX character classes can
2012 be used just like C<\d>, with the exception that POSIX character
2013 classes can only be used inside of a character class:
2014
2015     /\s+[abc[:digit:]xyz]\s*/;  # match a,b,c,x,y,z, or a digit
2016     /^=item\s[[:digit:]]/;      # match '=item',
2017                                 # followed by a space and a digit
2018     use charnames ":full";
2019     /\s+[abc\p{IsDigit}xyz]\s+/;  # match a,b,c,x,y,z, or a digit
2020     /^=item\s\p{IsDigit}/;        # match '=item',
2021                                   # followed by a space and a digit
2022
2023 Whew! That is all the rest of the characters and character classes.
2024
2025 =head2 Compiling and saving regular expressions
2026
2027 In Part 1 we discussed the C<//o> modifier, which compiles a regexp
2028 just once.  This suggests that a compiled regexp is some data structure
2029 that can be stored once and used again and again.  The regexp quote
2030 C<qr//> does exactly that: C<qr/string/> compiles the C<string> as a
2031 regexp and transforms the result into a form that can be assigned to a
2032 variable:
2033
2034     $reg = qr/foo+bar?/;  # reg contains a compiled regexp
2035
2036 Then C<$reg> can be used as a regexp:
2037
2038     $x = "fooooba";
2039     $x =~ $reg;     # matches, just like /foo+bar?/
2040     $x =~ /$reg/;   # same thing, alternate form
2041
2042 C<$reg> can also be interpolated into a larger regexp:
2043
2044     $x =~ /(abc)?$reg/;  # still matches
2045
2046 As with the matching operator, the regexp quote can use different
2047 delimiters, e.g., C<qr!!>, C<qr{}> or C<qr~~>.  Apostrophes
2048 as delimiters (C<qr''>) inhibit any interpolation.
2049
2050 Pre-compiled regexps are useful for creating dynamic matches that
2051 don't need to be recompiled each time they are encountered.  Using
2052 pre-compiled regexps, we write a C<grep_step> program which greps
2053 for a sequence of patterns, advancing to the next pattern as soon
2054 as one has been satisfied.
2055
2056     % cat > grep_step
2057     #!/usr/bin/perl
2058     # grep_step - match <number> regexps, one after the other
2059     # usage: multi_grep <number> regexp1 regexp2 ... file1 file2 ...
2060
2061     $number = shift;
2062     $regexp[$_] = shift foreach (0..$number-1);
2063     @compiled = map qr/$_/, @regexp;
2064     while ($line = <>) {
2065         if ($line =~ /$compiled[0]/) {
2066             print $line;
2067             shift @compiled;
2068             last unless @compiled;
2069         }
2070     }
2071     ^D
2072
2073     % grep_step 3 shift print last grep_step
2074     $number = shift;
2075             print $line;
2076             last unless @compiled;
2077
2078 Storing pre-compiled regexps in an array C<@compiled> allows us to
2079 simply loop through the regexps without any recompilation, thus gaining
2080 flexibility without sacrificing speed.
2081
2082
2083 =head2 Composing regular expressions at runtime
2084
2085 Backtracking is more efficient than repeated tries with different regular
2086 expressions.  If there are several regular expressions and a match with
2087 any of them is acceptable, then it is possible to combine them into a set
2088 of alternatives.  If the individual expressions are input data, this
2089 can be done by programming a join operation.  We'll exploit this idea in
2090 an improved version of the C<simple_grep> program: a program that matches
2091 multiple patterns:
2092
2093     % cat > multi_grep
2094     #!/usr/bin/perl
2095     # multi_grep - match any of <number> regexps
2096     # usage: multi_grep <number> regexp1 regexp2 ... file1 file2 ...
2097
2098     $number = shift;
2099     $regexp[$_] = shift foreach (0..$number-1);
2100     $pattern = join '|', @regexp;
2101
2102     while ($line = <>) {
2103         print $line if $line =~ /$pattern/o;
2104     }
2105     ^D
2106
2107     % multi_grep 2 shift for multi_grep
2108     $number = shift;
2109     $regexp[$_] = shift foreach (0..$number-1);
2110
2111 Sometimes it is advantageous to construct a pattern from the I<input>
2112 that is to be analyzed and use the permissible values on the left
2113 hand side of the matching operations.  As an example for this somewhat
2114 paradoxical situation, let's assume that our input contains a command
2115 verb which should match one out of a set of available command verbs,
2116 with the additional twist that commands may be abbreviated as long as
2117 the given string is unique. The program below demonstrates the basic
2118 algorithm.
2119
2120     % cat > keymatch
2121     #!/usr/bin/perl
2122     $kwds = 'copy compare list print';
2123     while( $command = <> ){
2124         $command =~ s/^\s+|\s+$//g;  # trim leading and trailing spaces
2125         if( ( @matches = $kwds =~ /\b$command\w*/g ) == 1 ){
2126             print "command: '@matches'\n";
2127         } elsif( @matches == 0 ){
2128             print "no such command: '$command'\n";
2129         } else {
2130             print "not unique: '$command' (could be one of: @matches)\n";
2131         }
2132     }
2133     ^D
2134
2135     % keymatch
2136     li
2137     command: 'list'
2138     co
2139     not unique: 'co' (could be one of: copy compare)
2140     printer
2141     no such command: 'printer'
2142
2143 Rather than trying to match the input against the keywords, we match the
2144 combined set of keywords against the input.  The pattern matching
2145 operation S<C<$kwds =~ /\b($command\w*)/g>> does several things at the
2146 same time. It makes sure that the given command begins where a keyword
2147 begins (C<\b>). It tolerates abbreviations due to the added C<\w*>. It
2148 tells us the number of matches (C<scalar @matches>) and all the keywords
2149 that were actually matched.  You could hardly ask for more.
2150
2151 =head2 Embedding comments and modifiers in a regular expression
2152
2153 Starting with this section, we will be discussing Perl's set of
2154 I<extended patterns>.  These are extensions to the traditional regular
2155 expression syntax that provide powerful new tools for pattern
2156 matching.  We have already seen extensions in the form of the minimal
2157 matching constructs C<??>, C<*?>, C<+?>, C<{n,m}?>, and C<{n,}?>.  The
2158 rest of the extensions below have the form C<(?char...)>, where the
2159 C<char> is a character that determines the type of extension.
2160
2161 The first extension is an embedded comment C<(?#text)>.  This embeds a
2162 comment into the regular expression without affecting its meaning.  The
2163 comment should not have any closing parentheses in the text.  An
2164 example is
2165
2166     /(?# Match an integer:)[+-]?\d+/;
2167
2168 This style of commenting has been largely superseded by the raw,
2169 freeform commenting that is allowed with the C<//x> modifier.
2170
2171 The modifiers C<//i>, C<//m>, C<//s> and C<//x> (or any
2172 combination thereof) can also be embedded in
2173 a regexp using C<(?i)>, C<(?m)>, C<(?s)>, and C<(?x)>.  For instance,
2174
2175     /(?i)yes/;  # match 'yes' case insensitively
2176     /yes/i;     # same thing
2177     /(?x)(          # freeform version of an integer regexp
2178              [+-]?  # match an optional sign
2179              \d+    # match a sequence of digits
2180          )
2181     /x;
2182
2183 Embedded modifiers can have two important advantages over the usual
2184 modifiers.  Embedded modifiers allow a custom set of modifiers to
2185 I<each> regexp pattern.  This is great for matching an array of regexps
2186 that must have different modifiers:
2187
2188     $pattern[0] = '(?i)doctor';
2189     $pattern[1] = 'Johnson';
2190     ...
2191     while (<>) {
2192         foreach $patt (@pattern) {
2193             print if /$patt/;
2194         }
2195     }
2196
2197 The second advantage is that embedded modifiers (except C<//p>, which
2198 modifies the entire regexp) only affect the regexp
2199 inside the group the embedded modifier is contained in.  So grouping
2200 can be used to localize the modifier's effects:
2201
2202     /Answer: ((?i)yes)/;  # matches 'Answer: yes', 'Answer: YES', etc.
2203
2204 Embedded modifiers can also turn off any modifiers already present
2205 by using, e.g., C<(?-i)>.  Modifiers can also be combined into
2206 a single expression, e.g., C<(?s-i)> turns on single line mode and
2207 turns off case insensitivity.
2208
2209 Embedded modifiers may also be added to a non-capturing grouping.
2210 C<(?i-m:regexp)> is a non-capturing grouping that matches C<regexp>
2211 case insensitively and turns off multi-line mode.
2212
2213
2214 =head2 Looking ahead and looking behind
2215
2216 This section concerns the lookahead and lookbehind assertions.  First,
2217 a little background.
2218
2219 In Perl regular expressions, most regexp elements 'eat up' a certain
2220 amount of string when they match.  For instance, the regexp element
2221 C<[abc}]> eats up one character of the string when it matches, in the
2222 sense that Perl moves to the next character position in the string
2223 after the match.  There are some elements, however, that don't eat up
2224 characters (advance the character position) if they match.  The examples
2225 we have seen so far are the anchors.  The anchor C<^> matches the
2226 beginning of the line, but doesn't eat any characters.  Similarly, the
2227 word boundary anchor C<\b> matches wherever a character matching C<\w>
2228 is next to a character that doesn't, but it doesn't eat up any
2229 characters itself.  Anchors are examples of I<zero-width assertions>.
2230 Zero-width, because they consume
2231 no characters, and assertions, because they test some property of the
2232 string.  In the context of our walk in the woods analogy to regexp
2233 matching, most regexp elements move us along a trail, but anchors have
2234 us stop a moment and check our surroundings.  If the local environment
2235 checks out, we can proceed forward.  But if the local environment
2236 doesn't satisfy us, we must backtrack.
2237
2238 Checking the environment entails either looking ahead on the trail,
2239 looking behind, or both.  C<^> looks behind, to see that there are no
2240 characters before.  C<$> looks ahead, to see that there are no
2241 characters after.  C<\b> looks both ahead and behind, to see if the
2242 characters on either side differ in their "word-ness".
2243
2244 The lookahead and lookbehind assertions are generalizations of the
2245 anchor concept.  Lookahead and lookbehind are zero-width assertions
2246 that let us specify which characters we want to test for.  The
2247 lookahead assertion is denoted by C<(?=regexp)> and the lookbehind
2248 assertion is denoted by C<< (?<=fixed-regexp) >>.  Some examples are
2249
2250     $x = "I catch the housecat 'Tom-cat' with catnip";
2251     $x =~ /cat(?=\s)/;   # matches 'cat' in 'housecat'
2252     @catwords = ($x =~ /(?<=\s)cat\w+/g);  # matches,
2253                                            # $catwords[0] = 'catch'
2254                                            # $catwords[1] = 'catnip'
2255     $x =~ /\bcat\b/;  # matches 'cat' in 'Tom-cat'
2256     $x =~ /(?<=\s)cat(?=\s)/; # doesn't match; no isolated 'cat' in
2257                               # middle of $x
2258
2259 Note that the parentheses in C<(?=regexp)> and C<< (?<=regexp) >> are
2260 non-capturing, since these are zero-width assertions.  Thus in the
2261 second regexp, the substrings captured are those of the whole regexp
2262 itself.  Lookahead C<(?=regexp)> can match arbitrary regexps, but
2263 lookbehind C<< (?<=fixed-regexp) >> only works for regexps of fixed
2264 width, i.e., a fixed number of characters long.  Thus
2265 C<< (?<=(ab|bc)) >> is fine, but C<< (?<=(ab)*) >> is not.  The
2266 negated versions of the lookahead and lookbehind assertions are
2267 denoted by C<(?!regexp)> and C<< (?<!fixed-regexp) >> respectively.
2268 They evaluate true if the regexps do I<not> match:
2269
2270     $x = "foobar";
2271     $x =~ /foo(?!bar)/;  # doesn't match, 'bar' follows 'foo'
2272     $x =~ /foo(?!baz)/;  # matches, 'baz' doesn't follow 'foo'
2273     $x =~ /(?<!\s)foo/;  # matches, there is no \s before 'foo'
2274
2275 The C<\C> is unsupported in lookbehind, because the already
2276 treacherous definition of C<\C> would become even more so
2277 when going backwards.
2278
2279 Here is an example where a string containing blank-separated words,
2280 numbers and single dashes is to be split into its components.
2281 Using C</\s+/> alone won't work, because spaces are not required between
2282 dashes, or a word or a dash. Additional places for a split are established
2283 by looking ahead and behind:
2284
2285     $str = "one two - --6-8";
2286     @toks = split / \s+              # a run of spaces
2287                   | (?<=\S) (?=-)    # any non-space followed by '-'
2288                   | (?<=-)  (?=\S)   # a '-' followed by any non-space
2289                   /x, $str;          # @toks = qw(one two - - - 6 - 8)
2290
2291
2292 =head2 Using independent subexpressions to prevent backtracking
2293
2294 I<Independent subexpressions> are regular expressions, in the
2295 context of a larger regular expression, that function independently of
2296 the larger regular expression.  That is, they consume as much or as
2297 little of the string as they wish without regard for the ability of
2298 the larger regexp to match.  Independent subexpressions are represented
2299 by C<< (?>regexp) >>.  We can illustrate their behavior by first
2300 considering an ordinary regexp:
2301
2302     $x = "ab";
2303     $x =~ /a*ab/;  # matches
2304
2305 This obviously matches, but in the process of matching, the
2306 subexpression C<a*> first grabbed the C<a>.  Doing so, however,
2307 wouldn't allow the whole regexp to match, so after backtracking, C<a*>
2308 eventually gave back the C<a> and matched the empty string.  Here, what
2309 C<a*> matched was I<dependent> on what the rest of the regexp matched.
2310
2311 Contrast that with an independent subexpression:
2312
2313     $x =~ /(?>a*)ab/;  # doesn't match!
2314
2315 The independent subexpression C<< (?>a*) >> doesn't care about the rest
2316 of the regexp, so it sees an C<a> and grabs it.  Then the rest of the
2317 regexp C<ab> cannot match.  Because C<< (?>a*) >> is independent, there
2318 is no backtracking and the independent subexpression does not give
2319 up its C<a>.  Thus the match of the regexp as a whole fails.  A similar
2320 behavior occurs with completely independent regexps:
2321
2322     $x = "ab";
2323     $x =~ /a*/g;   # matches, eats an 'a'
2324     $x =~ /\Gab/g; # doesn't match, no 'a' available
2325
2326 Here C<//g> and C<\G> create a 'tag team' handoff of the string from
2327 one regexp to the other.  Regexps with an independent subexpression are
2328 much like this, with a handoff of the string to the independent
2329 subexpression, and a handoff of the string back to the enclosing
2330 regexp.
2331
2332 The ability of an independent subexpression to prevent backtracking
2333 can be quite useful.  Suppose we want to match a non-empty string
2334 enclosed in parentheses up to two levels deep.  Then the following
2335 regexp matches:
2336
2337     $x = "abc(de(fg)h";  # unbalanced parentheses
2338     $x =~ /\( ( [^()]+ | \([^()]*\) )+ \)/x;
2339
2340 The regexp matches an open parenthesis, one or more copies of an
2341 alternation, and a close parenthesis.  The alternation is two-way, with
2342 the first alternative C<[^()]+> matching a substring with no
2343 parentheses and the second alternative C<\([^()]*\)>  matching a
2344 substring delimited by parentheses.  The problem with this regexp is
2345 that it is pathological: it has nested indeterminate quantifiers
2346 of the form C<(a+|b)+>.  We discussed in Part 1 how nested quantifiers
2347 like this could take an exponentially long time to execute if there
2348 was no match possible.  To prevent the exponential blowup, we need to
2349 prevent useless backtracking at some point.  This can be done by
2350 enclosing the inner quantifier as an independent subexpression:
2351
2352     $x =~ /\( ( (?>[^()]+) | \([^()]*\) )+ \)/x;
2353
2354 Here, C<< (?>[^()]+) >> breaks the degeneracy of string partitioning
2355 by gobbling up as much of the string as possible and keeping it.   Then
2356 match failures fail much more quickly.
2357
2358
2359 =head2 Conditional expressions
2360
2361 A I<conditional expression> is a form of if-then-else statement
2362 that allows one to choose which patterns are to be matched, based on
2363 some condition.  There are two types of conditional expression:
2364 C<(?(condition)yes-regexp)> and
2365 C<(?(condition)yes-regexp|no-regexp)>.  C<(?(condition)yes-regexp)> is
2366 like an S<C<'if () {}'>> statement in Perl.  If the C<condition> is true,
2367 the C<yes-regexp> will be matched.  If the C<condition> is false, the
2368 C<yes-regexp> will be skipped and Perl will move onto the next regexp
2369 element.  The second form is like an S<C<'if () {} else {}'>> statement
2370 in Perl.  If the C<condition> is true, the C<yes-regexp> will be
2371 matched, otherwise the C<no-regexp> will be matched.
2372
2373 The C<condition> can have several forms.  The first form is simply an
2374 integer in parentheses C<(integer)>.  It is true if the corresponding
2375 backreference C<\integer> matched earlier in the regexp.  The same
2376 thing can be done with a name associated with a capture group, written
2377 as C<< (<name>) >> or C<< ('name') >>.  The second form is a bare
2378 zero width assertion C<(?...)>, either a lookahead, a lookbehind, or a
2379 code assertion (discussed in the next section).  The third set of forms
2380 provides tests that return true if the expression is executed within
2381 a recursion (C<(R)>) or is being called from some capturing group,
2382 referenced either by number (C<(R1)>, C<(R2)>,...) or by name
2383 (C<(R&name)>).
2384
2385 The integer or name form of the C<condition> allows us to choose,
2386 with more flexibility, what to match based on what matched earlier in the
2387 regexp. This searches for words of the form C<"$x$x"> or C<"$x$y$y$x">:
2388
2389     % simple_grep '^(\w+)(\w+)?(?(2)\g2\g1|\g1)$' /usr/dict/words
2390     beriberi
2391     coco
2392     couscous
2393     deed
2394     ...
2395     toot
2396     toto
2397     tutu
2398
2399 The lookbehind C<condition> allows, along with backreferences,
2400 an earlier part of the match to influence a later part of the
2401 match.  For instance,
2402
2403     /[ATGC]+(?(?<=AA)G|C)$/;
2404
2405 matches a DNA sequence such that it either ends in C<AAG>, or some
2406 other base pair combination and C<C>.  Note that the form is
2407 C<< (?(?<=AA)G|C) >> and not C<< (?((?<=AA))G|C) >>; for the
2408 lookahead, lookbehind or code assertions, the parentheses around the
2409 conditional are not needed.
2410
2411
2412 =head2 Defining named patterns
2413
2414 Some regular expressions use identical subpatterns in several places.
2415 Starting with Perl 5.10, it is possible to define named subpatterns in
2416 a section of the pattern so that they can be called up by name
2417 anywhere in the pattern.  This syntactic pattern for this definition
2418 group is C<< (?(DEFINE)(?<name>pattern)...) >>.  An insertion
2419 of a named pattern is written as C<(?&name)>.
2420
2421 The example below illustrates this feature using the pattern for
2422 floating point numbers that was presented earlier on.  The three
2423 subpatterns that are used more than once are the optional sign, the
2424 digit sequence for an integer and the decimal fraction.  The DEFINE
2425 group at the end of the pattern contains their definition.  Notice
2426 that the decimal fraction pattern is the first place where we can
2427 reuse the integer pattern.
2428
2429    /^ (?&osg)\ * ( (?&int)(?&dec)? | (?&dec) )
2430       (?: [eE](?&osg)(?&int) )?
2431     $
2432     (?(DEFINE)
2433       (?<osg>[-+]?)         # optional sign
2434       (?<int>\d++)          # integer
2435       (?<dec>\.(?&int))     # decimal fraction
2436     )/x
2437
2438
2439 =head2 Recursive patterns
2440
2441 This feature (introduced in Perl 5.10) significantly extends the
2442 power of Perl's pattern matching.  By referring to some other
2443 capture group anywhere in the pattern with the construct
2444 C<(?group-ref)>, the I<pattern> within the referenced group is used
2445 as an independent subpattern in place of the group reference itself.
2446 Because the group reference may be contained I<within> the group it
2447 refers to, it is now possible to apply pattern matching to tasks that
2448 hitherto required a recursive parser.
2449
2450 To illustrate this feature, we'll design a pattern that matches if
2451 a string contains a palindrome. (This is a word or a sentence that,
2452 while ignoring spaces, interpunctuation and case, reads the same backwards
2453 as forwards. We begin by observing that the empty string or a string
2454 containing just one word character is a palindrome. Otherwise it must
2455 have a word character up front and the same at its end, with another
2456 palindrome in between.
2457
2458     /(?: (\w) (?...Here be a palindrome...) \g{-1} | \w? )/x
2459
2460 Adding C<\W*> at either end to eliminate what is to be ignored, we already
2461 have the full pattern:
2462
2463     my $pp = qr/^(\W* (?: (\w) (?1) \g{-1} | \w? ) \W*)$/ix;
2464     for $s ( "saippuakauppias", "A man, a plan, a canal: Panama!" ){
2465         print "'$s' is a palindrome\n" if $s =~ /$pp/;
2466     }
2467
2468 In C<(?...)> both absolute and relative backreferences may be used.
2469 The entire pattern can be reinserted with C<(?R)> or C<(?0)>.
2470 If you prefer to name your groups, you can use C<(?&name)> to
2471 recurse into that group.
2472
2473
2474 =head2 A bit of magic: executing Perl code in a regular expression
2475
2476 Normally, regexps are a part of Perl expressions.
2477 I<Code evaluation> expressions turn that around by allowing
2478 arbitrary Perl code to be a part of a regexp.  A code evaluation
2479 expression is denoted C<(?{code})>, with I<code> a string of Perl
2480 statements.
2481
2482 Be warned that this feature is considered experimental, and may be
2483 changed without notice.
2484
2485 Code expressions are zero-width assertions, and the value they return
2486 depends on their environment.  There are two possibilities: either the
2487 code expression is used as a conditional in a conditional expression
2488 C<(?(condition)...)>, or it is not.  If the code expression is a
2489 conditional, the code is evaluated and the result (i.e., the result of
2490 the last statement) is used to determine truth or falsehood.  If the
2491 code expression is not used as a conditional, the assertion always
2492 evaluates true and the result is put into the special variable
2493 C<$^R>.  The variable C<$^R> can then be used in code expressions later
2494 in the regexp.  Here are some silly examples:
2495
2496     $x = "abcdef";
2497     $x =~ /abc(?{print "Hi Mom!";})def/; # matches,
2498                                          # prints 'Hi Mom!'
2499     $x =~ /aaa(?{print "Hi Mom!";})def/; # doesn't match,
2500                                          # no 'Hi Mom!'
2501
2502 Pay careful attention to the next example:
2503
2504     $x =~ /abc(?{print "Hi Mom!";})ddd/; # doesn't match,
2505                                          # no 'Hi Mom!'
2506                                          # but why not?
2507
2508 At first glance, you'd think that it shouldn't print, because obviously
2509 the C<ddd> isn't going to match the target string. But look at this
2510 example:
2511
2512     $x =~ /abc(?{print "Hi Mom!";})[dD]dd/; # doesn't match,
2513                                             # but _does_ print
2514
2515 Hmm. What happened here? If you've been following along, you know that
2516 the above pattern should be effectively (almost) the same as the last one;
2517 enclosing the C<d> in a character class isn't going to change what it
2518 matches. So why does the first not print while the second one does?
2519
2520 The answer lies in the optimizations the regex engine makes. In the first
2521 case, all the engine sees are plain old characters (aside from the
2522 C<?{}> construct). It's smart enough to realize that the string 'ddd'
2523 doesn't occur in our target string before actually running the pattern
2524 through. But in the second case, we've tricked it into thinking that our
2525 pattern is more complicated. It takes a look, sees our
2526 character class, and decides that it will have to actually run the
2527 pattern to determine whether or not it matches, and in the process of
2528 running it hits the print statement before it discovers that we don't
2529 have a match.
2530
2531 To take a closer look at how the engine does optimizations, see the
2532 section L<"Pragmas and debugging"> below.
2533
2534 More fun with C<?{}>:
2535
2536     $x =~ /(?{print "Hi Mom!";})/;       # matches,
2537                                          # prints 'Hi Mom!'
2538     $x =~ /(?{$c = 1;})(?{print "$c";})/;  # matches,
2539                                            # prints '1'
2540     $x =~ /(?{$c = 1;})(?{print "$^R";})/; # matches,
2541                                            # prints '1'
2542
2543 The bit of magic mentioned in the section title occurs when the regexp
2544 backtracks in the process of searching for a match.  If the regexp
2545 backtracks over a code expression and if the variables used within are
2546 localized using C<local>, the changes in the variables produced by the
2547 code expression are undone! Thus, if we wanted to count how many times
2548 a character got matched inside a group, we could use, e.g.,
2549
2550     $x = "aaaa";
2551     $count = 0;  # initialize 'a' count
2552     $c = "bob";  # test if $c gets clobbered
2553     $x =~ /(?{local $c = 0;})         # initialize count
2554            ( a                        # match 'a'
2555              (?{local $c = $c + 1;})  # increment count
2556            )*                         # do this any number of times,
2557            aa                         # but match 'aa' at the end
2558            (?{$count = $c;})          # copy local $c var into $count
2559           /x;
2560     print "'a' count is $count, \$c variable is '$c'\n";
2561
2562 This prints
2563
2564     'a' count is 2, $c variable is 'bob'
2565
2566 If we replace the S<C< (?{local $c = $c + 1;})>> with
2567 S<C< (?{$c = $c + 1;})>>, the variable changes are I<not> undone
2568 during backtracking, and we get
2569
2570     'a' count is 4, $c variable is 'bob'
2571
2572 Note that only localized variable changes are undone.  Other side
2573 effects of code expression execution are permanent.  Thus
2574
2575     $x = "aaaa";
2576     $x =~ /(a(?{print "Yow\n";}))*aa/;
2577
2578 produces
2579
2580    Yow
2581    Yow
2582    Yow
2583    Yow
2584
2585 The result C<$^R> is automatically localized, so that it will behave
2586 properly in the presence of backtracking.
2587
2588 This example uses a code expression in a conditional to match a
2589 definite article, either 'the' in English or 'der|die|das' in German:
2590
2591     $lang = 'DE';  # use German
2592     ...
2593     $text = "das";
2594     print "matched\n"
2595         if $text =~ /(?(?{
2596                           $lang eq 'EN'; # is the language English?
2597                          })
2598                        the |             # if so, then match 'the'
2599                        (der|die|das)     # else, match 'der|die|das'
2600                      )
2601                     /xi;
2602
2603 Note that the syntax here is C<(?(?{...})yes-regexp|no-regexp)>, not
2604 C<(?((?{...}))yes-regexp|no-regexp)>.  In other words, in the case of a
2605 code expression, we don't need the extra parentheses around the
2606 conditional.
2607
2608 If you try to use code expressions with interpolating variables, Perl
2609 may surprise you:
2610
2611     $bar = 5;
2612     $pat = '(?{ 1 })';
2613     /foo(?{ $bar })bar/; # compiles ok, $bar not interpolated
2614     /foo(?{ 1 })$bar/;   # compile error!
2615     /foo${pat}bar/;      # compile error!
2616
2617     $pat = qr/(?{ $foo = 1 })/;  # precompile code regexp
2618     /foo${pat}bar/;      # compiles ok
2619
2620 If a regexp has (1) code expressions and interpolating variables, or
2621 (2) a variable that interpolates a code expression, Perl treats the
2622 regexp as an error. If the code expression is precompiled into a
2623 variable, however, interpolating is ok. The question is, why is this
2624 an error?
2625
2626 The reason is that variable interpolation and code expressions
2627 together pose a security risk.  The combination is dangerous because
2628 many programmers who write search engines often take user input and
2629 plug it directly into a regexp:
2630
2631     $regexp = <>;       # read user-supplied regexp
2632     $chomp $regexp;     # get rid of possible newline
2633     $text =~ /$regexp/; # search $text for the $regexp
2634
2635 If the C<$regexp> variable contains a code expression, the user could
2636 then execute arbitrary Perl code.  For instance, some joker could
2637 search for S<C<system('rm -rf *');>> to erase your files.  In this
2638 sense, the combination of interpolation and code expressions I<taints>
2639 your regexp.  So by default, using both interpolation and code
2640 expressions in the same regexp is not allowed.  If you're not
2641 concerned about malicious users, it is possible to bypass this
2642 security check by invoking S<C<use re 'eval'>>:
2643
2644     use re 'eval';       # throw caution out the door
2645     $bar = 5;
2646     $pat = '(?{ 1 })';
2647     /foo(?{ 1 })$bar/;   # compiles ok
2648     /foo${pat}bar/;      # compiles ok
2649
2650 Another form of code expression is the I<pattern code expression>.
2651 The pattern code expression is like a regular code expression, except
2652 that the result of the code evaluation is treated as a regular
2653 expression and matched immediately.  A simple example is
2654
2655     $length = 5;
2656     $char = 'a';
2657     $x = 'aaaaabb';
2658     $x =~ /(??{$char x $length})/x; # matches, there are 5 of 'a'
2659
2660
2661 This final example contains both ordinary and pattern code
2662 expressions.  It detects whether a binary string C<1101010010001...> has a
2663 Fibonacci spacing 0,1,1,2,3,5,...  of the C<1>'s:
2664
2665     $x = "1101010010001000001";
2666     $z0 = ''; $z1 = '0';   # initial conditions
2667     print "It is a Fibonacci sequence\n"
2668         if $x =~ /^1         # match an initial '1'
2669                     (?:
2670                        ((??{ $z0 })) # match some '0'
2671                        1             # and then a '1'
2672                        (?{ $z0 = $z1; $z1 .= $^N; })
2673                     )+   # repeat as needed
2674                   $      # that is all there is
2675                  /x;
2676     printf "Largest sequence matched was %d\n", length($z1)-length($z0);
2677
2678 Remember that C<$^N> is set to whatever was matched by the last
2679 completed capture group. This prints
2680
2681     It is a Fibonacci sequence
2682     Largest sequence matched was 5
2683
2684 Ha! Try that with your garden variety regexp package...
2685
2686 Note that the variables C<$z0> and C<$z1> are not substituted when the
2687 regexp is compiled, as happens for ordinary variables outside a code
2688 expression.  Rather, the code expressions are evaluated when Perl
2689 encounters them during the search for a match.
2690
2691 The regexp without the C<//x> modifier is
2692
2693     /^1(?:((??{ $z0 }))1(?{ $z0 = $z1; $z1 .= $^N; }))+$/
2694
2695 which shows that spaces are still possible in the code parts. Nevertheless,
2696 when working with code and conditional expressions, the extended form of
2697 regexps is almost necessary in creating and debugging regexps.
2698
2699
2700 =head2 Backtracking control verbs
2701
2702 Perl 5.10 introduced a number of control verbs intended to provide
2703 detailed control over the backtracking process, by directly influencing
2704 the regexp engine and by providing monitoring techniques.  As all
2705 the features in this group are experimental and subject to change or
2706 removal in a future version of Perl, the interested reader is
2707 referred to L<perlre/"Special Backtracking Control Verbs"> for a
2708 detailed description.
2709
2710 Below is just one example, illustrating the control verb C<(*FAIL)>,
2711 which may be abbreviated as C<(*F)>. If this is inserted in a regexp
2712 it will cause to fail, just like at some mismatch between the pattern
2713 and the string. Processing of the regexp continues like after any "normal"
2714 failure, so that, for instance, the next position in the string or another
2715 alternative will be tried. As failing to match doesn't preserve capture
2716 groups or produce results, it may be necessary to use this in
2717 combination with embedded code.
2718
2719    %count = ();
2720    "supercalifragilisticexpialidoceous" =~
2721        /([aeiou])(?{ $count{$1}++; })(*FAIL)/oi;
2722    printf "%3d '%s'\n", $count{$_}, $_ for (sort keys %count);
2723
2724 The pattern begins with a class matching a subset of letters.  Whenever
2725 this matches, a statement like C<$count{'a'}++;> is executed, incrementing
2726 the letter's counter. Then C<(*FAIL)> does what it says, and
2727 the regexp  engine proceeds according to the book: as long as the end of
2728 the string  hasn't been reached, the position is advanced before looking
2729 for another vowel. Thus, match or no match makes no difference, and the
2730 regexp engine proceeds until the entire string has been inspected.
2731 (It's remarkable that an alternative solution using something like
2732
2733    $count{lc($_)}++ for split('', "supercalifragilisticexpialidoceous");
2734    printf "%3d '%s'\n", $count2{$_}, $_ for ( qw{ a e i o u } );
2735
2736 is considerably slower.)
2737
2738
2739 =head2 Pragmas and debugging
2740
2741 Speaking of debugging, there are several pragmas available to control
2742 and debug regexps in Perl.  We have already encountered one pragma in
2743 the previous section, S<C<use re 'eval';>>, that allows variable
2744 interpolation and code expressions to coexist in a regexp.  The other
2745 pragmas are
2746
2747     use re 'taint';
2748     $tainted = <>;
2749     @parts = ($tainted =~ /(\w+)\s+(\w+)/; # @parts is now tainted
2750
2751 The C<taint> pragma causes any substrings from a match with a tainted
2752 variable to be tainted as well.  This is not normally the case, as
2753 regexps are often used to extract the safe bits from a tainted
2754 variable.  Use C<taint> when you are not extracting safe bits, but are
2755 performing some other processing.  Both C<taint> and C<eval> pragmas
2756 are lexically scoped, which means they are in effect only until
2757 the end of the block enclosing the pragmas.
2758
2759     use re 'debug';
2760     /^(.*)$/s;       # output debugging info
2761
2762     use re 'debugcolor';
2763     /^(.*)$/s;       # output debugging info in living color
2764
2765 The global C<debug> and C<debugcolor> pragmas allow one to get
2766 detailed debugging info about regexp compilation and
2767 execution.  C<debugcolor> is the same as debug, except the debugging
2768 information is displayed in color on terminals that can display
2769 termcap color sequences.  Here is example output:
2770
2771     % perl -e 'use re "debug"; "abc" =~ /a*b+c/;'
2772     Compiling REx `a*b+c'
2773     size 9 first at 1
2774        1: STAR(4)
2775        2:   EXACT <a>(0)
2776        4: PLUS(7)
2777        5:   EXACT <b>(0)
2778        7: EXACT <c>(9)
2779        9: END(0)
2780     floating `bc' at 0..2147483647 (checking floating) minlen 2
2781     Guessing start of match, REx `a*b+c' against `abc'...
2782     Found floating substr `bc' at offset 1...
2783     Guessed: match at offset 0
2784     Matching REx `a*b+c' against `abc'
2785       Setting an EVAL scope, savestack=3
2786        0 <> <abc>             |  1:  STAR
2787                                EXACT <a> can match 1 times out of 32767...
2788       Setting an EVAL scope, savestack=3
2789        1 <a> <bc>             |  4:    PLUS
2790                                EXACT <b> can match 1 times out of 32767...
2791       Setting an EVAL scope, savestack=3
2792        2 <ab> <c>             |  7:      EXACT <c>
2793        3 <abc> <>             |  9:      END
2794     Match successful!
2795     Freeing REx: `a*b+c'
2796
2797 If you have gotten this far into the tutorial, you can probably guess
2798 what the different parts of the debugging output tell you.  The first
2799 part
2800
2801     Compiling REx `a*b+c'
2802     size 9 first at 1
2803        1: STAR(4)
2804        2:   EXACT <a>(0)
2805        4: PLUS(7)
2806        5:   EXACT <b>(0)
2807        7: EXACT <c>(9)
2808        9: END(0)
2809
2810 describes the compilation stage.  C<STAR(4)> means that there is a
2811 starred object, in this case C<'a'>, and if it matches, goto line 4,
2812 i.e., C<PLUS(7)>.  The middle lines describe some heuristics and
2813 optimizations performed before a match:
2814
2815     floating `bc' at 0..2147483647 (checking floating) minlen 2
2816     Guessing start of match, REx `a*b+c' against `abc'...
2817     Found floating substr `bc' at offset 1...
2818     Guessed: match at offset 0
2819
2820 Then the match is executed and the remaining lines describe the
2821 process:
2822
2823     Matching REx `a*b+c' against `abc'
2824       Setting an EVAL scope, savestack=3
2825        0 <> <abc>             |  1:  STAR
2826                                EXACT <a> can match 1 times out of 32767...
2827       Setting an EVAL scope, savestack=3
2828        1 <a> <bc>             |  4:    PLUS
2829                                EXACT <b> can match 1 times out of 32767...
2830       Setting an EVAL scope, savestack=3
2831        2 <ab> <c>             |  7:      EXACT <c>
2832        3 <abc> <>             |  9:      END
2833     Match successful!
2834     Freeing REx: `a*b+c'
2835
2836 Each step is of the form S<C<< n <x> <y> >>>, with C<< <x> >> the
2837 part of the string matched and C<< <y> >> the part not yet
2838 matched.  The S<C<< |  1:  STAR >>> says that Perl is at line number 1
2839 n the compilation list above.  See
2840 L<perldebguts/"Debugging regular expressions"> for much more detail.
2841
2842 An alternative method of debugging regexps is to embed C<print>
2843 statements within the regexp.  This provides a blow-by-blow account of
2844 the backtracking in an alternation:
2845
2846     "that this" =~ m@(?{print "Start at position ", pos, "\n";})
2847                      t(?{print "t1\n";})
2848                      h(?{print "h1\n";})
2849                      i(?{print "i1\n";})
2850                      s(?{print "s1\n";})
2851                          |
2852                      t(?{print "t2\n";})
2853                      h(?{print "h2\n";})
2854                      a(?{print "a2\n";})
2855                      t(?{print "t2\n";})
2856                      (?{print "Done at position ", pos, "\n";})
2857                     @x;
2858
2859 prints
2860
2861     Start at position 0
2862     t1
2863     h1
2864     t2
2865     h2
2866     a2
2867     t2
2868     Done at position 4
2869
2870 =head1 BUGS
2871
2872 Code expressions, conditional expressions, and independent expressions
2873 are I<experimental>.  Don't use them in production code.  Yet.
2874
2875 =head1 SEE ALSO
2876
2877 This is just a tutorial.  For the full story on Perl regular
2878 expressions, see the L<perlre> regular expressions reference page.
2879
2880 For more information on the matching C<m//> and substitution C<s///>
2881 operators, see L<perlop/"Regexp Quote-Like Operators">.  For
2882 information on the C<split> operation, see L<perlfunc/split>.
2883
2884 For an excellent all-around resource on the care and feeding of
2885 regular expressions, see the book I<Mastering Regular Expressions> by
2886 Jeffrey Friedl (published by O'Reilly, ISBN 1556592-257-3).
2887
2888 =head1 AUTHOR AND COPYRIGHT
2889
2890 Copyright (c) 2000 Mark Kvale
2891 All rights reserved.
2892
2893 This document may be distributed under the same terms as Perl itself.
2894
2895 =head2 Acknowledgments
2896
2897 The inspiration for the stop codon DNA example came from the ZIP
2898 code example in chapter 7 of I<Mastering Regular Expressions>.
2899
2900 The author would like to thank Jeff Pinyan, Andrew Johnson, Peter
2901 Haworth, Ronald J Kimball, and Joe Smith for all their helpful
2902 comments.
2903
2904 =cut
2905