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