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