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