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