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