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