3 perlretut - Perl regular expressions tutorial
7 This page provides a basic tutorial on understanding, creating and
8 using regular expressions in Perl. It serves as a complement to the
9 reference page on regular expressions L<perlre>. Regular expressions
10 are an integral part of the C<m//>, C<s///>, C<qr//> and C<split>
11 operators and so this tutorial also overlaps with
12 L<perlop/"Regexp Quote-Like Operators"> and L<perlfunc/split>.
14 Perl is widely renowned for excellence in text processing, and regular
15 expressions are one of the big factors behind this fame. Perl regular
16 expressions display an efficiency and flexibility unknown in most
17 other computer languages. Mastering even the basics of regular
18 expressions will allow you to manipulate text with surprising ease.
20 What is a regular expression? A regular expression is simply a string
21 that describes a pattern. Patterns are in common use these days;
22 examples are the patterns typed into a search engine to find web pages
23 and the patterns used to list files in a directory, e.g., C<ls *.txt>
24 or C<dir *.*>. In Perl, the patterns described by regular expressions
25 are used to search strings, extract desired parts of strings, and to
26 do search and replace operations.
28 Regular expressions have the undeserved reputation of being abstract
29 and difficult to understand. Regular expressions are constructed using
30 simple concepts like conditionals and loops and are no more difficult
31 to understand than the corresponding C<if> conditionals and C<while>
32 loops in the Perl language itself. In fact, the main challenge in
33 learning regular expressions is just getting used to the terse
34 notation used to express these concepts.
36 This tutorial flattens the learning curve by discussing regular
37 expression concepts, along with their notation, one at a time and with
38 many examples. The first part of the tutorial will progress from the
39 simplest word searches to the basic regular expression concepts. If
40 you master the first part, you will have all the tools needed to solve
41 about 98% of your needs. The second part of the tutorial is for those
42 comfortable with the basics and hungry for more power tools. It
43 discusses the more advanced regular expression operators and
44 introduces the latest cutting edge innovations in 5.6.0.
46 A note: to save time, 'regular expression' is often abbreviated as
47 regexp or regex. Regexp is a more natural abbreviation than regex, but
48 is harder to pronounce. The Perl pod documentation is evenly split on
49 regexp vs regex; in Perl, there is more than one way to abbreviate it.
50 We'll use regexp in this tutorial.
52 =head1 Part 1: The basics
54 =head2 Simple word matching
56 The simplest regexp is simply a word, or more generally, a string of
57 characters. A regexp consisting of a word matches any string that
60 "Hello World" =~ /World/; # matches
62 What is this Perl statement all about? C<"Hello World"> is a simple
63 double quoted string. C<World> is the regular expression and the
64 C<//> enclosing C</World/> tells Perl to search a string for a match.
65 The operator C<=~> associates the string with the regexp match and
66 produces a true value if the regexp matched, or false if the regexp
67 did not match. In our case, C<World> matches the second word in
68 C<"Hello World">, so the expression is true. Expressions like this
69 are useful in conditionals:
71 if ("Hello World" =~ /World/) {
75 print "It doesn't match\n";
78 There are useful variations on this theme. The sense of the match can
79 be reversed by using the C<!~> operator:
81 if ("Hello World" !~ /World/) {
82 print "It doesn't match\n";
88 The literal string in the regexp can be replaced by a variable:
91 if ("Hello World" =~ /$greeting/) {
95 print "It doesn't match\n";
98 If you're matching against the special default variable C<$_>, the
99 C<$_ =~> part can be omitted:
103 print "It matches\n";
106 print "It doesn't match\n";
109 And finally, the C<//> default delimiters for a match can be changed
110 to arbitrary delimiters by putting an C<'m'> out front:
112 "Hello World" =~ m!World!; # matches, delimited by '!'
113 "Hello World" =~ m{World}; # matches, note the matching '{}'
114 "/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin',
115 # '/' becomes an ordinary char
117 C</World/>, C<m!World!>, and C<m{World}> all represent the
118 same thing. When, e.g., the quote (C<">) is used as a delimiter, the forward
119 slash C<'/'> becomes an ordinary character and can be used in this regexp
122 Let's consider how different regexps would match C<"Hello World">:
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
129 The first regexp C<world> doesn't match because regexps are
130 case-sensitive. The second regexp matches because the substring
131 S<C<'o W'>> occurs in the string S<C<"Hello World">>. The space
132 character ' ' is treated like any other character in a regexp and is
133 needed to match in this case. The lack of a space character is the
134 reason the third regexp C<'oW'> doesn't match. The fourth regexp
135 C<'World '> doesn't match because there is a space at the end of the
136 regexp, but not at the end of the string. The lesson here is that
137 regexps must match a part of the string I<exactly> in order for the
138 statement to be true.
140 If a regexp matches in more than one place in the string, Perl will
141 always match at the earliest possible point in the string:
143 "Hello World" =~ /o/; # matches 'o' in 'Hello'
144 "That hat is red" =~ /hat/; # matches 'hat' in 'That'
146 With respect to character matching, there are a few more points you
147 need to know about. First of all, not all characters can be used 'as
148 is' in a match. Some characters, called I<metacharacters>, are reserved
149 for use in regexp notation. The metacharacters are
153 The significance of each of these will be explained
154 in the rest of the tutorial, but for now, it is important only to know
155 that a metacharacter can be matched by putting a backslash before it:
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
161 "#!/usr/bin/perl" =~ /#!\/usr\/bin\/perl/; # matches
163 In the last regexp, the forward slash C<'/'> is also backslashed,
164 because it is used to delimit the regexp. This can lead to LTS
165 (leaning toothpick syndrome), however, and it is often more readable
166 to change delimiters.
168 "#!/usr/bin/perl" =~ m!#\!/usr/bin/perl!; # easier to read
170 The backslash character C<'\'> is a metacharacter itself and needs to
173 'C:\WIN32' =~ /C:\\WIN/; # matches
175 In addition to the metacharacters, there are some ASCII characters
176 which don't have printable character equivalents and are instead
177 represented by I<escape sequences>. Common examples are C<\t> for a
178 tab, C<\n> for a newline, C<\r> for a carriage return and C<\a> for a
179 bell. If your string is better thought of as a sequence of arbitrary
180 bytes, the octal escape sequence, e.g., C<\033>, or hexadecimal escape
181 sequence, e.g., C<\x1B> may be a more natural representation for your
182 bytes. Here are some examples of escapes:
184 "1000\t2000" =~ m(0\t2) # matches
185 "1000\n2000" =~ /0\n20/ # matches
186 "1000\t2000" =~ /\000\t2/ # doesn't match, "0" ne "\000"
187 "cat" =~ /\143\x61\x74/ # matches, but a weird way to spell cat
189 If you've been around Perl a while, all this talk of escape sequences
190 may seem familiar. Similar escape sequences are used in double-quoted
191 strings and in fact the regexps in Perl are mostly treated as
192 double-quoted strings. This means that variables can be used in
193 regexps as well. Just like double-quoted strings, the values of the
194 variables in the regexp will be substituted in before the regexp is
195 evaluated for matching purposes. So we have:
198 'housecat' =~ /$foo/; # matches
199 'cathouse' =~ /cat$foo/; # matches
200 'housecat' =~ /${foo}cat/; # matches
202 So far, so good. With the knowledge above you can already perform
203 searches with just about any literal string regexp you can dream up.
204 Here is a I<very simple> emulation of the Unix grep program:
214 % chmod +x simple_grep
216 % simple_grep abba /usr/dict/words
227 This program is easy to understand. C<#!/usr/bin/perl> is the standard
228 way to invoke a perl program from the shell.
229 S<C<$regexp = shift;>> saves the first command line argument as the
230 regexp to be used, leaving the rest of the command line arguments to
231 be treated as files. S<C<< while (<>) >>> loops over all the lines in
232 all the files. For each line, S<C<print if /$regexp/;>> prints the
233 line if the regexp matches the line. In this line, both C<print> and
234 C</$regexp/> use the default variable C<$_> implicitly.
236 With all of the regexps above, if the regexp matched anywhere in the
237 string, it was considered a match. Sometimes, however, we'd like to
238 specify I<where> in the string the regexp should try to match. To do
239 this, we would use the I<anchor> metacharacters C<^> and C<$>. The
240 anchor C<^> means match at the beginning of the string and the anchor
241 C<$> means match at the end of the string, or before a newline at the
242 end of the string. Here is how they are used:
244 "housekeeper" =~ /keeper/; # matches
245 "housekeeper" =~ /^keeper/; # doesn't match
246 "housekeeper" =~ /keeper$/; # matches
247 "housekeeper\n" =~ /keeper$/; # matches
249 The second regexp doesn't match because C<^> constrains C<keeper> to
250 match only at the beginning of the string, but C<"housekeeper"> has
251 keeper starting in the middle. The third regexp does match, since the
252 C<$> constrains C<keeper> to match only at the end of the string.
254 When both C<^> and C<$> are used at the same time, the regexp has to
255 match both the beginning and the end of the string, i.e., the regexp
256 matches the whole string. Consider
258 "keeper" =~ /^keep$/; # doesn't match
259 "keeper" =~ /^keeper$/; # matches
260 "" =~ /^$/; # ^$ matches an empty string
262 The first regexp doesn't match because the string has more to it than
263 C<keep>. Since the second regexp is exactly the string, it
264 matches. Using both C<^> and C<$> in a regexp forces the complete
265 string to match, so it gives you complete control over which strings
266 match and which don't. Suppose you are looking for a fellow named
267 bert, off in a string by himself:
269 "dogbert" =~ /bert/; # matches, but not what you want
271 "dilbert" =~ /^bert/; # doesn't match, but ..
272 "bertram" =~ /^bert/; # matches, so still not good enough
274 "bertram" =~ /^bert$/; # doesn't match, good
275 "dilbert" =~ /^bert$/; # doesn't match, good
276 "bert" =~ /^bert$/; # matches, perfect
278 Of course, in the case of a literal string, one could just as easily
279 use the string comparison S<C<$string eq 'bert'>> and it would be
280 more efficient. The C<^...$> regexp really becomes useful when we
281 add in the more powerful regexp tools below.
283 =head2 Using character classes
285 Although one can already do quite a lot with the literal string
286 regexps above, we've only scratched the surface of regular expression
287 technology. In this and subsequent sections we will introduce regexp
288 concepts (and associated metacharacter notations) that will allow a
289 regexp to not just represent a single character sequence, but a I<whole
292 One such concept is that of a I<character class>. A character class
293 allows a set of possible characters, rather than just a single
294 character, to match at a particular point in a regexp. Character
295 classes are denoted by brackets C<[...]>, with the set of characters
296 to be possibly matched inside. Here are some examples:
298 /cat/; # matches 'cat'
299 /[bcr]at/; # matches 'bat, 'cat', or 'rat'
300 /item[0123456789]/; # matches 'item0' or ... or 'item9'
301 "abc" =~ /[cab]/; # matches 'a'
303 In the last statement, even though C<'c'> is the first character in
304 the class, C<'a'> matches because the first character position in the
305 string is the earliest point at which the regexp can match.
307 /[yY][eE][sS]/; # match 'yes' in a case-insensitive way
308 # 'yes', 'Yes', 'YES', etc.
310 This regexp displays a common task: perform a case-insensitive
311 match. Perl provides a way of avoiding all those brackets by simply
312 appending an C<'i'> to the end of the match. Then C</[yY][eE][sS]/;>
313 can be rewritten as C</yes/i;>. The C<'i'> stands for
314 case-insensitive and is an example of a I<modifier> of the matching
315 operation. We will meet other modifiers later in the tutorial.
317 We saw in the section above that there were ordinary characters, which
318 represented themselves, and special characters, which needed a
319 backslash C<\> to represent themselves. The same is true in a
320 character class, but the sets of ordinary and special characters
321 inside a character class are different than those outside a character
322 class. The special characters for a character class are C<-]\^$> (and
323 the pattern delimiter, whatever it is).
324 C<]> is special because it denotes the end of a character class. C<$> is
325 special because it denotes a scalar variable. C<\> is special because
326 it is used in escape sequences, just like above. Here is how the
327 special characters C<]$\> are handled:
329 /[\]c]def/; # matches ']def' or 'cdef'
331 /[$x]at/; # matches 'bat', 'cat', or 'rat'
332 /[\$x]at/; # matches '$at' or 'xat'
333 /[\\$x]at/; # matches '\at', 'bat, 'cat', or 'rat'
335 The last two are a little tricky. In C<[\$x]>, the backslash protects
336 the dollar sign, so the character class has two members C<$> and C<x>.
337 In C<[\\$x]>, the backslash is protected, so C<$x> is treated as a
338 variable and substituted in double quote fashion.
340 The special character C<'-'> acts as a range operator within character
341 classes, so that a contiguous set of characters can be written as a
342 range. With ranges, the unwieldy C<[0123456789]> and C<[abc...xyz]>
343 become the svelte C<[0-9]> and C<[a-z]>. Some examples are
345 /item[0-9]/; # matches 'item0' or ... or 'item9'
346 /[0-9bx-z]aa/; # matches '0aa', ..., '9aa',
347 # 'baa', 'xaa', 'yaa', or 'zaa'
348 /[0-9a-fA-F]/; # matches a hexadecimal digit
349 /[0-9a-zA-Z_]/; # matches a "word" character,
350 # like those in a Perl variable name
352 If C<'-'> is the first or last character in a character class, it is
353 treated as an ordinary character; C<[-ab]>, C<[ab-]> and C<[a\-b]> are
356 The special character C<^> in the first position of a character class
357 denotes a I<negated character class>, which matches any character but
358 those in the brackets. Both C<[...]> and C<[^...]> must match a
359 character, or the match fails. Then
361 /[^a]at/; # doesn't match 'aat' or 'at', but matches
362 # all other 'bat', 'cat, '0at', '%at', etc.
363 /[^0-9]/; # matches a non-numeric character
364 /[a^]at/; # matches 'aat' or '^at'; here '^' is ordinary
366 Now, even C<[0-9]> can be a bother to write multiple times, so in the
367 interest of saving keystrokes and making regexps more readable, Perl
368 has several abbreviations for common character classes, as shown below.
369 Since the introduction of Unicode, these character classes match more
370 than just a few characters in the ISO 8859-1 range.
376 \d matches a digit, not just [0-9] but also digits from non-roman scripts
380 \s matches a whitespace character, the set [\ \t\r\n\f] and others
384 \w matches a word character (alphanumeric or _), not just [0-9a-zA-Z_]
385 but also digits and characters from non-roman scripts
389 \D is a negated \d; it represents any other character than a digit, or [^\d]
393 \S is a negated \s; it represents any non-whitespace character [^\s]
397 \W is a negated \w; it represents any non-word character [^\w]
401 The period '.' matches any character but "\n" (unless the modifier C<//s> is
402 in effect, as explained below).
406 The C<\d\s\w\D\S\W> abbreviations can be used both inside and outside
407 of character classes. Here are some in use:
409 /\d\d:\d\d:\d\d/; # matches a hh:mm:ss time format
410 /[\d\s]/; # matches any digit or whitespace character
411 /\w\W\w/; # matches a word char, followed by a
412 # non-word char, followed by a word char
413 /..rt/; # matches any two chars, followed by 'rt'
414 /end\./; # matches 'end.'
415 /end[.]/; # same thing, matches 'end.'
417 Because a period is a metacharacter, it needs to be escaped to match
418 as an ordinary period. Because, for example, C<\d> and C<\w> are sets
419 of characters, it is incorrect to think of C<[^\d\w]> as C<[\D\W]>; in
420 fact C<[^\d\w]> is the same as C<[^\w]>, which is the same as
421 C<[\W]>. Think DeMorgan's laws.
423 An anchor useful in basic regexps is the I<word anchor>
424 C<\b>. This matches a boundary between a word character and a non-word
425 character C<\w\W> or C<\W\w>:
427 $x = "Housecat catenates house and cat";
428 $x =~ /cat/; # matches cat in 'housecat'
429 $x =~ /\bcat/; # matches cat in 'catenates'
430 $x =~ /cat\b/; # matches cat in 'housecat'
431 $x =~ /\bcat\b/; # matches 'cat' at end of string
433 Note in the last example, the end of the string is considered a word
436 You might wonder why C<'.'> matches everything but C<"\n"> - why not
437 every character? The reason is that often one is matching against
438 lines and would like to ignore the newline characters. For instance,
439 while the string C<"\n"> represents one line, we would like to think
442 "" =~ /^$/; # matches
443 "\n" =~ /^$/; # matches, $ anchors before "\n"
445 "" =~ /./; # doesn't match; it needs a char
446 "" =~ /^.$/; # doesn't match; it needs a char
447 "\n" =~ /^.$/; # doesn't match; it needs a char other than "\n"
448 "a" =~ /^.$/; # matches
449 "a\n" =~ /^.$/; # matches, $ anchors before "\n"
451 This behavior is convenient, because we usually want to ignore
452 newlines when we count and match characters in a line. Sometimes,
453 however, we want to keep track of newlines. We might even want C<^>
454 and C<$> to anchor at the beginning and end of lines within the
455 string, rather than just the beginning and end of the string. Perl
456 allows us to choose between ignoring and paying attention to newlines
457 by using the C<//s> and C<//m> modifiers. C<//s> and C<//m> stand for
458 single line and multi-line and they determine whether a string is to
459 be treated as one continuous string, or as a set of lines. The two
460 modifiers affect two aspects of how the regexp is interpreted: 1) how
461 the C<'.'> character class is defined, and 2) where the anchors C<^>
462 and C<$> are able to match. Here are the four possible combinations:
468 no modifiers (//): Default behavior. C<'.'> matches any character
469 except C<"\n">. C<^> matches only at the beginning of the string and
470 C<$> matches only at the end or before a newline at the end.
474 s modifier (//s): Treat string as a single long line. C<'.'> matches
475 any character, even C<"\n">. C<^> matches only at the beginning of
476 the string and C<$> matches only at the end or before a newline at the
481 m modifier (//m): Treat string as a set of multiple lines. C<'.'>
482 matches any character except C<"\n">. C<^> and C<$> are able to match
483 at the start or end of I<any> line within the string.
487 both s and m modifiers (//sm): Treat string as a single long line, but
488 detect multiple lines. C<'.'> matches any character, even
489 C<"\n">. C<^> and C<$>, however, are able to match at the start or end
490 of I<any> line within the string.
494 Here are examples of C<//s> and C<//m> in action:
496 $x = "There once was a girl\nWho programmed in Perl\n";
498 $x =~ /^Who/; # doesn't match, "Who" not at start of string
499 $x =~ /^Who/s; # doesn't match, "Who" not at start of string
500 $x =~ /^Who/m; # matches, "Who" at start of second line
501 $x =~ /^Who/sm; # matches, "Who" at start of second line
503 $x =~ /girl.Who/; # doesn't match, "." doesn't match "\n"
504 $x =~ /girl.Who/s; # matches, "." matches "\n"
505 $x =~ /girl.Who/m; # doesn't match, "." doesn't match "\n"
506 $x =~ /girl.Who/sm; # matches, "." matches "\n"
508 Most of the time, the default behavior is what is wanted, but C<//s> and
509 C<//m> are occasionally very useful. If C<//m> is being used, the start
510 of the string can still be matched with C<\A> and the end of the string
511 can still be matched with the anchors C<\Z> (matches both the end and
512 the newline before, like C<$>), and C<\z> (matches only the end):
514 $x =~ /^Who/m; # matches, "Who" at start of second line
515 $x =~ /\AWho/m; # doesn't match, "Who" is not at start of string
517 $x =~ /girl$/m; # matches, "girl" at end of first line
518 $x =~ /girl\Z/m; # doesn't match, "girl" is not at end of string
520 $x =~ /Perl\Z/m; # matches, "Perl" is at newline before end
521 $x =~ /Perl\z/m; # doesn't match, "Perl" is not at end of string
523 We now know how to create choices among classes of characters in a
524 regexp. What about choices among words or character strings? Such
525 choices are described in the next section.
527 =head2 Matching this or that
529 Sometimes we would like our regexp to be able to match different
530 possible words or character strings. This is accomplished by using
531 the I<alternation> metacharacter C<|>. To match C<dog> or C<cat>, we
532 form the regexp C<dog|cat>. As before, Perl will try to match the
533 regexp at the earliest possible point in the string. At each
534 character position, Perl will first try to match the first
535 alternative, C<dog>. If C<dog> doesn't match, Perl will then try the
536 next alternative, C<cat>. If C<cat> doesn't match either, then the
537 match fails and Perl moves to the next position in the string. Some
540 "cats and dogs" =~ /cat|dog|bird/; # matches "cat"
541 "cats and dogs" =~ /dog|cat|bird/; # matches "cat"
543 Even though C<dog> is the first alternative in the second regexp,
544 C<cat> is able to match earlier in the string.
546 "cats" =~ /c|ca|cat|cats/; # matches "c"
547 "cats" =~ /cats|cat|ca|c/; # matches "cats"
549 Here, all the alternatives match at the first string position, so the
550 first alternative is the one that matches. If some of the
551 alternatives are truncations of the others, put the longest ones first
552 to give them a chance to match.
554 "cab" =~ /a|b|c/ # matches "c"
557 The last example points out that character classes are like
558 alternations of characters. At a given character position, the first
559 alternative that allows the regexp match to succeed will be the one
562 =head2 Grouping things and hierarchical matching
564 Alternation allows a regexp to choose among alternatives, but by
565 itself it is unsatisfying. The reason is that each alternative is a whole
566 regexp, but sometime we want alternatives for just part of a
567 regexp. For instance, suppose we want to search for housecats or
568 housekeepers. The regexp C<housecat|housekeeper> fits the bill, but is
569 inefficient because we had to type C<house> twice. It would be nice to
570 have parts of the regexp be constant, like C<house>, and some
571 parts have alternatives, like C<cat|keeper>.
573 The I<grouping> metacharacters C<()> solve this problem. Grouping
574 allows parts of a regexp to be treated as a single unit. Parts of a
575 regexp are grouped by enclosing them in parentheses. Thus we could solve
576 the C<housecat|housekeeper> by forming the regexp as
577 C<house(cat|keeper)>. The regexp C<house(cat|keeper)> means match
578 C<house> followed by either C<cat> or C<keeper>. Some more examples
581 /(a|b)b/; # matches 'ab' or 'bb'
582 /(ac|b)b/; # matches 'acb' or 'bb'
583 /(^a|b)c/; # matches 'ac' at start of string or 'bc' anywhere
584 /(a|[bc])d/; # matches 'ad', 'bd', or 'cd'
586 /house(cat|)/; # matches either 'housecat' or 'house'
587 /house(cat(s|)|)/; # matches either 'housecats' or 'housecat' or
588 # 'house'. Note groups can be nested.
590 /(19|20|)\d\d/; # match years 19xx, 20xx, or the Y2K problem, xx
591 "20" =~ /(19|20|)\d\d/; # matches the null alternative '()\d\d',
592 # because '20\d\d' can't match
594 Alternations behave the same way in groups as out of them: at a given
595 string position, the leftmost alternative that allows the regexp to
596 match is taken. So in the last example at the first string position,
597 C<"20"> matches the second alternative, but there is nothing left over
598 to match the next two digits C<\d\d>. So Perl moves on to the next
599 alternative, which is the null alternative and that works, since
600 C<"20"> is two digits.
602 The process of trying one alternative, seeing if it matches, and
603 moving on to the next alternative, while going back in the string
604 from where the previous alternative was tried, if it doesn't, is called
605 I<backtracking>. The term 'backtracking' comes from the idea that
606 matching a regexp is like a walk in the woods. Successfully matching
607 a regexp is like arriving at a destination. There are many possible
608 trailheads, one for each string position, and each one is tried in
609 order, left to right. From each trailhead there may be many paths,
610 some of which get you there, and some which are dead ends. When you
611 walk along a trail and hit a dead end, you have to backtrack along the
612 trail to an earlier point to try another trail. If you hit your
613 destination, you stop immediately and forget about trying all the
614 other trails. You are persistent, and only if you have tried all the
615 trails from all the trailheads and not arrived at your destination, do
616 you declare failure. To be concrete, here is a step-by-step analysis
617 of what Perl does when it tries to match the regexp
619 "abcde" =~ /(abd|abc)(df|d|de)/;
625 Start with the first letter in the string 'a'.
629 Try the first alternative in the first group 'abd'.
633 Match 'a' followed by 'b'. So far so good.
637 'd' in the regexp doesn't match 'c' in the string - a dead
638 end. So backtrack two characters and pick the second alternative in
639 the first group 'abc'.
643 Match 'a' followed by 'b' followed by 'c'. We are on a roll
644 and have satisfied the first group. Set $1 to 'abc'.
648 Move on to the second group and pick the first alternative
657 'f' in the regexp doesn't match 'e' in the string, so a dead
658 end. Backtrack one character and pick the second alternative in the
663 'd' matches. The second grouping is satisfied, so set $2 to
668 We are at the end of the regexp, so we are done! We have
669 matched 'abcd' out of the string "abcde".
673 There are a couple of things to note about this analysis. First, the
674 third alternative in the second group 'de' also allows a match, but we
675 stopped before we got to it - at a given character position, leftmost
676 wins. Second, we were able to get a match at the first character
677 position of the string 'a'. If there were no matches at the first
678 position, Perl would move to the second character position 'b' and
679 attempt the match all over again. Only when all possible paths at all
680 possible character positions have been exhausted does Perl give
681 up and declare S<C<$string =~ /(abd|abc)(df|d|de)/;>> to be false.
683 Even with all this work, regexp matching happens remarkably fast. To
684 speed things up, Perl compiles the regexp into a compact sequence of
685 opcodes that can often fit inside a processor cache. When the code is
686 executed, these opcodes can then run at full throttle and search very
689 =head2 Extracting matches
691 The grouping metacharacters C<()> also serve another completely
692 different function: they allow the extraction of the parts of a string
693 that matched. This is very useful to find out what matched and for
694 text processing in general. For each grouping, the part that matched
695 inside goes into the special variables C<$1>, C<$2>, etc. They can be
696 used just as ordinary variables:
698 # extract hours, minutes, seconds
699 if ($time =~ /(\d\d):(\d\d):(\d\d)/) { # match hh:mm:ss format
705 Now, we know that in scalar context,
706 S<C<$time =~ /(\d\d):(\d\d):(\d\d)/>> returns a true or false
707 value. In list context, however, it returns the list of matched values
708 C<($1,$2,$3)>. So we could write the code more compactly as
710 # extract hours, minutes, seconds
711 ($hours, $minutes, $second) = ($time =~ /(\d\d):(\d\d):(\d\d)/);
713 If the groupings in a regexp are nested, C<$1> gets the group with the
714 leftmost opening parenthesis, C<$2> the next opening parenthesis,
715 etc. Here is a regexp with nested groups:
717 /(ab(cd|ef)((gi)|j))/;
720 If this regexp matches, C<$1> contains a string starting with
721 C<'ab'>, C<$2> is either set to C<'cd'> or C<'ef'>, C<$3> equals either
722 C<'gi'> or C<'j'>, and C<$4> is either set to C<'gi'>, just like C<$3>,
723 or it remains undefined.
725 For convenience, Perl sets C<$+> to the string held by the highest numbered
726 C<$1>, C<$2>,... that got assigned (and, somewhat related, C<$^N> to the
727 value of the C<$1>, C<$2>,... most-recently assigned; i.e. the C<$1>,
728 C<$2>,... associated with the rightmost closing parenthesis used in the
732 =head2 Backreferences
734 Closely associated with the matching variables C<$1>, C<$2>, ... are
735 the I<backreferences> C<\1>, C<\2>,... Backreferences are simply
736 matching variables that can be used I<inside> a regexp. This is a
737 really nice feature; what matches later in a regexp is made to depend on
738 what matched earlier in the regexp. Suppose we wanted to look
739 for doubled words in a text, like 'the the'. The following regexp finds
740 all 3-letter doubles with a space in between:
744 The grouping assigns a value to \1, so that the same 3 letter sequence
745 is used for both parts.
747 A similar task is to find words consisting of two identical parts:
749 % simple_grep '^(\w\w\w\w|\w\w\w|\w\w|\w)\1$' /usr/dict/words
757 The regexp has a single grouping which considers 4-letter
758 combinations, then 3-letter combinations, etc., and uses C<\1> to look for
759 a repeat. Although C<$1> and C<\1> represent the same thing, care should be
760 taken to use matched variables C<$1>, C<$2>,... only I<outside> a regexp
761 and backreferences C<\1>, C<\2>,... only I<inside> a regexp; not doing
762 so may lead to surprising and unsatisfactory results.
765 =head2 Relative backreferences
767 Counting the opening parentheses to get the correct number for a
768 backreference is errorprone as soon as there is more than one
769 capturing group. A more convenient technique became available
770 with Perl 5.10: relative backreferences. To refer to the immediately
771 preceding capture group one now may write C<\g{-1}>, the next but
772 last is available via C<\g{-2}>, and so on.
774 Another good reason in addition to readability and maintainability
775 for using relative backreferences is illustrated by the following example,
776 where a simple pattern for matching peculiar strings is used:
778 $a99a = '([a-z])(\d)\2\1'; # matches a11a, g22g, x33x, etc.
780 Now that we have this pattern stored as a handy string, we might feel
781 tempted to use it as a part of some other pattern:
784 if ($line =~ /^(\w+)=$a99a$/){ # unexpected behavior!
785 print "$1 is valid\n";
787 print "bad line: '$line'\n";
790 But this doesn't match, at least not the way one might expect. Only
791 after inserting the interpolated C<$a99a> and looking at the resulting
792 full text of the regexp is it obvious that the backreferences have
793 backfired. The subexpression C<(\w+)> has snatched number 1 and
794 demoted the groups in C<$a99a> by one rank. This can be avoided by
795 using relative backreferences:
797 $a99a = '([a-z])(\d)\g{-1}\g{-2}'; # safe for being interpolated
800 =head2 Named backreferences
802 Perl 5.10 also introduced named capture buffers and named backreferences.
803 To attach a name to a capturing group, you write either
804 C<< (?<name>...) >> or C<< (?'name'...) >>. The backreference may
805 then be written as C<\g{name}>. It is permissible to attach the
806 same name to more than one group, but then only the leftmost one of the
807 eponymous set can be referenced. Outside of the pattern a named
808 capture buffer is accessible through the C<%+> hash.
810 Assuming that we have to match calendar dates which may be given in one
811 of the three formats yyyy-mm-dd, mm/dd/yyyy or dd.mm.yyyy, we can write
812 three suitable patterns where we use 'd', 'm' and 'y' respectively as the
813 names of the buffers capturing the pertaining components of a date. The
814 matching operation combines the three patterns as alternatives:
816 $fmt1 = '(?<y>\d\d\d\d)-(?<m>\d\d)-(?<d>\d\d)';
817 $fmt2 = '(?<m>\d\d)/(?<d>\d\d)/(?<y>\d\d\d\d)';
818 $fmt3 = '(?<d>\d\d)\.(?<m>\d\d)\.(?<y>\d\d\d\d)';
819 for my $d qw( 2006-10-21 15.01.2007 10/31/2005 ){
820 if ( $d =~ m{$fmt1|$fmt2|$fmt3} ){
821 print "day=$+{d} month=$+{m} year=$+{y}\n";
825 If any of the alternatives matches, the hash C<%+> is bound to contain the
826 three key-value pairs.
829 =head2 Alternative capture group numbering
831 Yet another capturing group numbering technique (also as from Perl 5.10)
832 deals with the problem of referring to groups within a set of alternatives.
833 Consider a pattern for matching a time of the day, civil or military style:
835 if ( $time =~ /(\d\d|\d):(\d\d)|(\d\d)(\d\d)/ ){
836 # process hour and minute
839 Processing the results requires an additional if statement to determine
840 whether C<$1> and C<$2> or C<$3> and C<$4> contain the goodies. It would
841 be easier if we could use buffer numbers 1 and 2 in second alternative as
842 well, and this is exactly what the parenthesized construct C<(?|...)>,
843 set around an alternative achieves. Here is an extended version of the
846 if ( $time =~ /(?|(\d\d|\d):(\d\d)|(\d\d)(\d\d))\s+([A-Z][A-Z][A-Z])/ ){
847 print "hour=$1 minute=$2 zone=$3\n";
850 Within the alternative numbering group, buffer numbers start at the same
851 position for each alternative. After the group, numbering continues
852 with one higher than the maximum reached across all the alternatives.
854 =head2 Position information
856 In addition to what was matched, Perl (since 5.6.0) also provides the
857 positions of what was matched as contents of the C<@-> and C<@+>
858 arrays. C<$-[0]> is the position of the start of the entire match and
859 C<$+[0]> is the position of the end. Similarly, C<$-[n]> is the
860 position of the start of the C<$n> match and C<$+[n]> is the position
861 of the end. If C<$n> is undefined, so are C<$-[n]> and C<$+[n]>. Then
864 $x = "Mmm...donut, thought Homer";
865 $x =~ /^(Mmm|Yech)\.\.\.(donut|peas)/; # matches
866 foreach $expr (1..$#-) {
867 print "Match $expr: '${$expr}' at position ($-[$expr],$+[$expr])\n";
872 Match 1: 'Mmm' at position (0,3)
873 Match 2: 'donut' at position (6,11)
875 Even if there are no groupings in a regexp, it is still possible to
876 find out what exactly matched in a string. If you use them, Perl
877 will set C<$`> to the part of the string before the match, will set C<$&>
878 to the part of the string that matched, and will set C<$'> to the part
879 of the string after the match. An example:
881 $x = "the cat caught the mouse";
882 $x =~ /cat/; # $` = 'the ', $& = 'cat', $' = ' caught the mouse'
883 $x =~ /the/; # $` = '', $& = 'the', $' = ' cat caught the mouse'
885 In the second match, C<$`> equals C<''> because the regexp matched at the
886 first character position in the string and stopped; it never saw the
887 second 'the'. It is important to note that using C<$`> and C<$'>
888 slows down regexp matching quite a bit, while C<$&> slows it down to a
889 lesser extent, because if they are used in one regexp in a program,
890 they are generated for I<all> regexps in the program. So if raw
891 performance is a goal of your application, they should be avoided.
892 If you need to extract the corresponding substrings, use C<@-> and
895 $` is the same as substr( $x, 0, $-[0] )
896 $& is the same as substr( $x, $-[0], $+[0]-$-[0] )
897 $' is the same as substr( $x, $+[0] )
900 =head2 Non-capturing groupings
902 A group that is required to bundle a set of alternatives may or may not be
903 useful as a capturing group. If it isn't, it just creates a superfluous
904 addition to the set of available capture buffer values, inside as well as
905 outside the regexp. Non-capturing groupings, denoted by C<(?:regexp)>,
906 still allow the regexp to be treated as a single unit, but don't establish
907 a capturing buffer at the same time. Both capturing and non-capturing
908 groupings are allowed to co-exist in the same regexp. Because there is
909 no extraction, non-capturing groupings are faster than capturing
910 groupings. Non-capturing groupings are also handy for choosing exactly
911 which parts of a regexp are to be extracted to matching variables:
913 # match a number, $1-$4 are set, but we only want $1
914 /([+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)/;
916 # match a number faster , only $1 is set
917 /([+-]?\ *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)/;
919 # match a number, get $1 = whole number, $2 = exponent
920 /([+-]?\ *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE]([+-]?\d+))?)/;
922 Non-capturing groupings are also useful for removing nuisance
923 elements gathered from a split operation where parentheses are
924 required for some reason:
927 @num = split /(a|b)+/, $x; # @num = ('12','a','34','b','5')
928 @num = split /(?:a|b)+/, $x; # @num = ('12','34','5')
931 =head2 Matching repetitions
933 The examples in the previous section display an annoying weakness. We
934 were only matching 3-letter words, or chunks of words of 4 letters or
935 less. We'd like to be able to match words or, more generally, strings
936 of any length, without writing out tedious alternatives like
937 C<\w\w\w\w|\w\w\w|\w\w|\w>.
939 This is exactly the problem the I<quantifier> metacharacters C<?>,
940 C<*>, C<+>, and C<{}> were created for. They allow us to delimit the
941 number of repeats for a portion of a regexp we consider to be a
942 match. Quantifiers are put immediately after the character, character
943 class, or grouping that we want to specify. They have the following
950 C<a?> means: match 'a' 1 or 0 times
954 C<a*> means: match 'a' 0 or more times, i.e., any number of times
958 C<a+> means: match 'a' 1 or more times, i.e., at least once
962 C<a{n,m}> means: match at least C<n> times, but not more than C<m>
967 C<a{n,}> means: match at least C<n> or more times
971 C<a{n}> means: match exactly C<n> times
975 Here are some examples:
977 /[a-z]+\s+\d*/; # match a lowercase word, at least one space, and
978 # any number of digits
979 /(\w+)\s+\1/; # match doubled words of arbitrary length
980 /y(es)?/i; # matches 'y', 'Y', or a case-insensitive 'yes'
981 $year =~ /\d{2,4}/; # make sure year is at least 2 but not more
983 $year =~ /\d{4}|\d{2}/; # better match; throw out 3 digit dates
984 $year =~ /\d{2}(\d{2})?/; # same thing written differently. However,
985 # this produces $1 and the other does not.
987 % simple_grep '^(\w+)\1$' /usr/dict/words # isn't this easier?
995 For all of these quantifiers, Perl will try to match as much of the
996 string as possible, while still allowing the regexp to succeed. Thus
997 with C</a?.../>, Perl will first try to match the regexp with the C<a>
998 present; if that fails, Perl will try to match the regexp without the
999 C<a> present. For the quantifier C<*>, we get the following:
1001 $x = "the cat in the hat";
1002 $x =~ /^(.*)(cat)(.*)$/; # matches,
1005 # $3 = ' in the hat'
1007 Which is what we might expect, the match finds the only C<cat> in the
1008 string and locks onto it. Consider, however, this regexp:
1010 $x =~ /^(.*)(at)(.*)$/; # matches,
1011 # $1 = 'the cat in the h'
1013 # $3 = '' (0 characters match)
1015 One might initially guess that Perl would find the C<at> in C<cat> and
1016 stop there, but that wouldn't give the longest possible string to the
1017 first quantifier C<.*>. Instead, the first quantifier C<.*> grabs as
1018 much of the string as possible while still having the regexp match. In
1019 this example, that means having the C<at> sequence with the final C<at>
1020 in the string. The other important principle illustrated here is that
1021 when there are two or more elements in a regexp, the I<leftmost>
1022 quantifier, if there is one, gets to grab as much the string as
1023 possible, leaving the rest of the regexp to fight over scraps. Thus in
1024 our example, the first quantifier C<.*> grabs most of the string, while
1025 the second quantifier C<.*> gets the empty string. Quantifiers that
1026 grab as much of the string as possible are called I<maximal match> or
1027 I<greedy> quantifiers.
1029 When a regexp can match a string in several different ways, we can use
1030 the principles above to predict which way the regexp will match:
1036 Principle 0: Taken as a whole, any regexp will be matched at the
1037 earliest possible position in the string.
1041 Principle 1: In an alternation C<a|b|c...>, the leftmost alternative
1042 that allows a match for the whole regexp will be the one used.
1046 Principle 2: The maximal matching quantifiers C<?>, C<*>, C<+> and
1047 C<{n,m}> will in general match as much of the string as possible while
1048 still allowing the whole regexp to match.
1052 Principle 3: If there are two or more elements in a regexp, the
1053 leftmost greedy quantifier, if any, will match as much of the string
1054 as possible while still allowing the whole regexp to match. The next
1055 leftmost greedy quantifier, if any, will try to match as much of the
1056 string remaining available to it as possible, while still allowing the
1057 whole regexp to match. And so on, until all the regexp elements are
1062 As we have seen above, Principle 0 overrides the others. The regexp
1063 will be matched as early as possible, with the other principles
1064 determining how the regexp matches at that earliest character
1067 Here is an example of these principles in action:
1069 $x = "The programming republic of Perl";
1070 $x =~ /^(.+)(e|r)(.*)$/; # matches,
1071 # $1 = 'The programming republic of Pe'
1075 This regexp matches at the earliest string position, C<'T'>. One
1076 might think that C<e>, being leftmost in the alternation, would be
1077 matched, but C<r> produces the longest string in the first quantifier.
1079 $x =~ /(m{1,2})(.*)$/; # matches,
1081 # $2 = 'ing republic of Perl'
1083 Here, The earliest possible match is at the first C<'m'> in
1084 C<programming>. C<m{1,2}> is the first quantifier, so it gets to match
1087 $x =~ /.*(m{1,2})(.*)$/; # matches,
1089 # $2 = 'ing republic of Perl'
1091 Here, the regexp matches at the start of the string. The first
1092 quantifier C<.*> grabs as much as possible, leaving just a single
1093 C<'m'> for the second quantifier C<m{1,2}>.
1095 $x =~ /(.?)(m{1,2})(.*)$/; # matches,
1098 # $3 = 'ing republic of Perl'
1100 Here, C<.?> eats its maximal one character at the earliest possible
1101 position in the string, C<'a'> in C<programming>, leaving C<m{1,2}>
1102 the opportunity to match both C<m>'s. Finally,
1104 "aXXXb" =~ /(X*)/; # matches with $1 = ''
1106 because it can match zero copies of C<'X'> at the beginning of the
1107 string. If you definitely want to match at least one C<'X'>, use
1110 Sometimes greed is not good. At times, we would like quantifiers to
1111 match a I<minimal> piece of string, rather than a maximal piece. For
1112 this purpose, Larry Wall created the I<minimal match> or
1113 I<non-greedy> quantifiers C<??>, C<*?>, C<+?>, and C<{}?>. These are
1114 the usual quantifiers with a C<?> appended to them. They have the
1121 C<a??> means: match 'a' 0 or 1 times. Try 0 first, then 1.
1125 C<a*?> means: match 'a' 0 or more times, i.e., any number of times,
1126 but as few times as possible
1130 C<a+?> means: match 'a' 1 or more times, i.e., at least once, but
1131 as few times as possible
1135 C<a{n,m}?> means: match at least C<n> times, not more than C<m>
1136 times, as few times as possible
1140 C<a{n,}?> means: match at least C<n> times, but as few times as
1145 C<a{n}?> means: match exactly C<n> times. Because we match exactly
1146 C<n> times, C<a{n}?> is equivalent to C<a{n}> and is just there for
1147 notational consistency.
1151 Let's look at the example above, but with minimal quantifiers:
1153 $x = "The programming republic of Perl";
1154 $x =~ /^(.+?)(e|r)(.*)$/; # matches,
1157 # $3 = ' programming republic of Perl'
1159 The minimal string that will allow both the start of the string C<^>
1160 and the alternation to match is C<Th>, with the alternation C<e|r>
1161 matching C<e>. The second quantifier C<.*> is free to gobble up the
1164 $x =~ /(m{1,2}?)(.*?)$/; # matches,
1166 # $2 = 'ming republic of Perl'
1168 The first string position that this regexp can match is at the first
1169 C<'m'> in C<programming>. At this position, the minimal C<m{1,2}?>
1170 matches just one C<'m'>. Although the second quantifier C<.*?> would
1171 prefer to match no characters, it is constrained by the end-of-string
1172 anchor C<$> to match the rest of the string.
1174 $x =~ /(.*?)(m{1,2}?)(.*)$/; # matches,
1177 # $3 = 'ming republic of Perl'
1179 In this regexp, you might expect the first minimal quantifier C<.*?>
1180 to match the empty string, because it is not constrained by a C<^>
1181 anchor to match the beginning of the word. Principle 0 applies here,
1182 however. Because it is possible for the whole regexp to match at the
1183 start of the string, it I<will> match at the start of the string. Thus
1184 the first quantifier has to match everything up to the first C<m>. The
1185 second minimal quantifier matches just one C<m> and the third
1186 quantifier matches the rest of the string.
1188 $x =~ /(.??)(m{1,2})(.*)$/; # matches,
1191 # $3 = 'ing republic of Perl'
1193 Just as in the previous regexp, the first quantifier C<.??> can match
1194 earliest at position C<'a'>, so it does. The second quantifier is
1195 greedy, so it matches C<mm>, and the third matches the rest of the
1198 We can modify principle 3 above to take into account non-greedy
1205 Principle 3: If there are two or more elements in a regexp, the
1206 leftmost greedy (non-greedy) quantifier, if any, will match as much
1207 (little) of the string as possible while still allowing the whole
1208 regexp to match. The next leftmost greedy (non-greedy) quantifier, if
1209 any, will try to match as much (little) of the string remaining
1210 available to it as possible, while still allowing the whole regexp to
1211 match. And so on, until all the regexp elements are satisfied.
1215 Just like alternation, quantifiers are also susceptible to
1216 backtracking. Here is a step-by-step analysis of the example
1218 $x = "the cat in the hat";
1219 $x =~ /^(.*)(at)(.*)$/; # matches,
1220 # $1 = 'the cat in the h'
1222 # $3 = '' (0 matches)
1228 Start with the first letter in the string 't'.
1232 The first quantifier '.*' starts out by matching the whole
1233 string 'the cat in the hat'.
1237 'a' in the regexp element 'at' doesn't match the end of the
1238 string. Backtrack one character.
1242 'a' in the regexp element 'at' still doesn't match the last
1243 letter of the string 't', so backtrack one more character.
1247 Now we can match the 'a' and the 't'.
1251 Move on to the third element '.*'. Since we are at the end of
1252 the string and '.*' can match 0 times, assign it the empty string.
1260 Most of the time, all this moving forward and backtracking happens
1261 quickly and searching is fast. There are some pathological regexps,
1262 however, whose execution time exponentially grows with the size of the
1263 string. A typical structure that blows up in your face is of the form
1267 The problem is the nested indeterminate quantifiers. There are many
1268 different ways of partitioning a string of length n between the C<+>
1269 and C<*>: one repetition with C<b+> of length n, two repetitions with
1270 the first C<b+> length k and the second with length n-k, m repetitions
1271 whose bits add up to length n, etc. In fact there are an exponential
1272 number of ways to partition a string as a function of its length. A
1273 regexp may get lucky and match early in the process, but if there is
1274 no match, Perl will try I<every> possibility before giving up. So be
1275 careful with nested C<*>'s, C<{n,m}>'s, and C<+>'s. The book
1276 I<Mastering Regular Expressions> by Jeffrey Friedl gives a wonderful
1277 discussion of this and other efficiency issues.
1280 =head2 Possessive quantifiers
1282 Backtracking during the relentless search for a match may be a waste
1283 of time, particularly when the match is bound to fail. Consider
1286 /^\w+\s+\w+$/; # a word, spaces, a word
1288 Whenever this is applied to a string which doesn't quite meet the
1289 pattern's expectations such as S<C<"abc ">> or S<C<"abc def ">>,
1290 the regex engine will backtrack, approximately once for each character
1291 in the string. But we know that there is no way around taking I<all>
1292 of the initial word characters to match the first repetition, that I<all>
1293 spaces must be eaten by the middle part, and the same goes for the second
1296 With the introduction of the I<possessive quantifiers> in Perl 5.10, we
1297 have a way of instructing the regex engine not to backtrack, with the
1298 usual quantifiers with a C<+> appended to them. This makes them greedy as
1299 well as stingy; once they succeed they won't give anything back to permit
1300 another solution. They have the following meanings:
1306 C<a{n,m}+> means: match at least C<n> times, not more than C<m> times,
1307 as many times as possible, and don't give anything up. C<a?+> is short
1312 C<a{n,}+> means: match at least C<n> times, but as many times as possible,
1313 and don't give anything up. C<a*+> is short for C<a{0,}+> and C<a++> is
1314 short for C<a{1,}+>.
1318 C<a{n}+> means: match exactly C<n> times. It is just there for
1319 notational consistency.
1323 These possessive quantifiers represent a special case of a more general
1324 concept, the I<independent subexpression>, see below.
1326 As an example where a possessive quantifier is suitable we consider
1327 matching a quoted string, as it appears in several programming languages.
1328 The backslash is used as an escape character that indicates that the
1329 next character is to be taken literally, as another character for the
1330 string. Therefore, after the opening quote, we expect a (possibly
1331 empty) sequence of alternatives: either some character except an
1332 unescaped quote or backslash or an escaped character.
1334 /"(?:[^"\\]++|\\.)*+"/;
1337 =head2 Building a regexp
1339 At this point, we have all the basic regexp concepts covered, so let's
1340 give a more involved example of a regular expression. We will build a
1341 regexp that matches numbers.
1343 The first task in building a regexp is to decide what we want to match
1344 and what we want to exclude. In our case, we want to match both
1345 integers and floating point numbers and we want to reject any string
1346 that isn't a number.
1348 The next task is to break the problem down into smaller problems that
1349 are easily converted into a regexp.
1351 The simplest case is integers. These consist of a sequence of digits,
1352 with an optional sign in front. The digits we can represent with
1353 C<\d+> and the sign can be matched with C<[+-]>. Thus the integer
1356 /[+-]?\d+/; # matches integers
1358 A floating point number potentially has a sign, an integral part, a
1359 decimal point, a fractional part, and an exponent. One or more of these
1360 parts is optional, so we need to check out the different
1361 possibilities. Floating point numbers which are in proper form include
1362 123., 0.345, .34, -1e6, and 25.4E-72. As with integers, the sign out
1363 front is completely optional and can be matched by C<[+-]?>. We can
1364 see that if there is no exponent, floating point numbers must have a
1365 decimal point, otherwise they are integers. We might be tempted to
1366 model these with C<\d*\.\d*>, but this would also match just a single
1367 decimal point, which is not a number. So the three cases of floating
1368 point number without exponent are
1370 /[+-]?\d+\./; # 1., 321., etc.
1371 /[+-]?\.\d+/; # .1, .234, etc.
1372 /[+-]?\d+\.\d+/; # 1.0, 30.56, etc.
1374 These can be combined into a single regexp with a three-way alternation:
1376 /[+-]?(\d+\.\d+|\d+\.|\.\d+)/; # floating point, no exponent
1378 In this alternation, it is important to put C<'\d+\.\d+'> before
1379 C<'\d+\.'>. If C<'\d+\.'> were first, the regexp would happily match that
1380 and ignore the fractional part of the number.
1382 Now consider floating point numbers with exponents. The key
1383 observation here is that I<both> integers and numbers with decimal
1384 points are allowed in front of an exponent. Then exponents, like the
1385 overall sign, are independent of whether we are matching numbers with
1386 or without decimal points, and can be 'decoupled' from the
1387 mantissa. The overall form of the regexp now becomes clear:
1389 /^(optional sign)(integer | f.p. mantissa)(optional exponent)$/;
1391 The exponent is an C<e> or C<E>, followed by an integer. So the
1394 /[eE][+-]?\d+/; # exponent
1396 Putting all the parts together, we get a regexp that matches numbers:
1398 /^[+-]?(\d+\.\d+|\d+\.|\.\d+|\d+)([eE][+-]?\d+)?$/; # Ta da!
1400 Long regexps like this may impress your friends, but can be hard to
1401 decipher. In complex situations like this, the C<//x> modifier for a
1402 match is invaluable. It allows one to put nearly arbitrary whitespace
1403 and comments into a regexp without affecting their meaning. Using it,
1404 we can rewrite our 'extended' regexp in the more pleasing form
1407 [+-]? # first, match an optional sign
1408 ( # then match integers or f.p. mantissas:
1409 \d+\.\d+ # mantissa of the form a.b
1410 |\d+\. # mantissa of the form a.
1411 |\.\d+ # mantissa of the form .b
1412 |\d+ # integer of the form a
1414 ([eE][+-]?\d+)? # finally, optionally match an exponent
1417 If whitespace is mostly irrelevant, how does one include space
1418 characters in an extended regexp? The answer is to backslash it
1419 S<C<'\ '>> or put it in a character class S<C<[ ]>>. The same thing
1420 goes for pound signs, use C<\#> or C<[#]>. For instance, Perl allows
1421 a space between the sign and the mantissa or integer, and we could add
1422 this to our regexp as follows:
1425 [+-]?\ * # first, match an optional sign *and space*
1426 ( # then match integers or f.p. mantissas:
1427 \d+\.\d+ # mantissa of the form a.b
1428 |\d+\. # mantissa of the form a.
1429 |\.\d+ # mantissa of the form .b
1430 |\d+ # integer of the form a
1432 ([eE][+-]?\d+)? # finally, optionally match an exponent
1435 In this form, it is easier to see a way to simplify the
1436 alternation. Alternatives 1, 2, and 4 all start with C<\d+>, so it
1437 could be factored out:
1440 [+-]?\ * # first, match an optional sign
1441 ( # then match integers or f.p. mantissas:
1442 \d+ # start out with a ...
1444 \.\d* # mantissa of the form a.b or a.
1445 )? # ? takes care of integers of the form a
1446 |\.\d+ # mantissa of the form .b
1448 ([eE][+-]?\d+)? # finally, optionally match an exponent
1451 or written in the compact form,
1453 /^[+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/;
1455 This is our final regexp. To recap, we built a regexp by
1461 specifying the task in detail,
1465 breaking down the problem into smaller parts,
1469 translating the small parts into regexps,
1473 combining the regexps,
1477 and optimizing the final combined regexp.
1481 These are also the typical steps involved in writing a computer
1482 program. This makes perfect sense, because regular expressions are
1483 essentially programs written in a little computer language that specifies
1486 =head2 Using regular expressions in Perl
1488 The last topic of Part 1 briefly covers how regexps are used in Perl
1489 programs. Where do they fit into Perl syntax?
1491 We have already introduced the matching operator in its default
1492 C</regexp/> and arbitrary delimiter C<m!regexp!> forms. We have used
1493 the binding operator C<=~> and its negation C<!~> to test for string
1494 matches. Associated with the matching operator, we have discussed the
1495 single line C<//s>, multi-line C<//m>, case-insensitive C<//i> and
1496 extended C<//x> modifiers. There are a few more things you might
1497 want to know about matching operators.
1499 =head3 Optimizing pattern evaluation
1501 We pointed out earlier that variables in regexps are substituted
1502 before the regexp is evaluated:
1506 print if /$pattern/;
1509 This will print any lines containing the word C<Seuss>. It is not as
1510 efficient as it could be, however, because Perl has to re-evaluate
1511 (or compile) C<$pattern> each time through the loop. If C<$pattern> won't be
1512 changing over the lifetime of the script, we can add the C<//o>
1513 modifier, which directs Perl to only perform variable substitutions
1517 # Improved simple_grep
1520 print if /$regexp/o; # a good deal faster
1524 =head3 Prohibiting substitution
1526 If you change C<$pattern> after the first substitution happens, Perl
1527 will ignore it. If you don't want any substitutions at all, use the
1528 special delimiter C<m''>:
1530 @pattern = ('Seuss');
1532 print if m'@pattern'; # matches literal '@pattern', not 'Seuss'
1535 Similar to strings, C<m''> acts like apostrophes on a regexp; all other
1536 C<m> delimiters act like quotes. If the regexp evaluates to the empty string,
1537 the regexp in the I<last successful match> is used instead. So we have
1539 "dog" =~ /d/; # 'd' matches
1540 "dogbert =~ //; # this matches the 'd' regexp used before
1543 =head3 Global matching
1545 The final two modifiers C<//g> and C<//c> concern multiple matches.
1546 The modifier C<//g> stands for global matching and allows the
1547 matching operator to match within a string as many times as possible.
1548 In scalar context, successive invocations against a string will have
1549 `C<//g> jump from match to match, keeping track of position in the
1550 string as it goes along. You can get or set the position with the
1553 The use of C<//g> is shown in the following example. Suppose we have
1554 a string that consists of words separated by spaces. If we know how
1555 many words there are in advance, we could extract the words using
1558 $x = "cat dog house"; # 3 words
1559 $x =~ /^\s*(\w+)\s+(\w+)\s+(\w+)\s*$/; # matches,
1564 But what if we had an indeterminate number of words? This is the sort
1565 of task C<//g> was made for. To extract all words, form the simple
1566 regexp C<(\w+)> and loop over all matches with C</(\w+)/g>:
1568 while ($x =~ /(\w+)/g) {
1569 print "Word is $1, ends at position ", pos $x, "\n";
1574 Word is cat, ends at position 3
1575 Word is dog, ends at position 7
1576 Word is house, ends at position 13
1578 A failed match or changing the target string resets the position. If
1579 you don't want the position reset after failure to match, add the
1580 C<//c>, as in C</regexp/gc>. The current position in the string is
1581 associated with the string, not the regexp. This means that different
1582 strings have different positions and their respective positions can be
1583 set or read independently.
1585 In list context, C<//g> returns a list of matched groupings, or if
1586 there are no groupings, a list of matches to the whole regexp. So if
1587 we wanted just the words, we could use
1589 @words = ($x =~ /(\w+)/g); # matches,
1592 # $word[2] = 'house'
1594 Closely associated with the C<//g> modifier is the C<\G> anchor. The
1595 C<\G> anchor matches at the point where the previous C<//g> match left
1596 off. C<\G> allows us to easily do context-sensitive matching:
1598 $metric = 1; # use metric units
1600 $x = <FILE>; # read in measurement
1601 $x =~ /^([+-]?\d+)\s*/g; # get magnitude
1603 if ($metric) { # error checking
1604 print "Units error!" unless $x =~ /\Gkg\./g;
1607 print "Units error!" unless $x =~ /\Glbs\./g;
1609 $x =~ /\G\s+(widget|sprocket)/g; # continue processing
1611 The combination of C<//g> and C<\G> allows us to process the string a
1612 bit at a time and use arbitrary Perl logic to decide what to do next.
1613 Currently, the C<\G> anchor is only fully supported when used to anchor
1614 to the start of the pattern.
1616 C<\G> is also invaluable in processing fixed length records with
1617 regexps. Suppose we have a snippet of coding region DNA, encoded as
1618 base pair letters C<ATCGTTGAAT...> and we want to find all the stop
1619 codons C<TGA>. In a coding region, codons are 3-letter sequences, so
1620 we can think of the DNA snippet as a sequence of 3-letter records. The
1623 # expanded, this is "ATC GTT GAA TGC AAA TGA CAT GAC"
1624 $dna = "ATCGTTGAATGCAAATGACATGAC";
1627 doesn't work; it may match a C<TGA>, but there is no guarantee that
1628 the match is aligned with codon boundaries, e.g., the substring
1629 S<C<GTT GAA>> gives a match. A better solution is
1631 while ($dna =~ /(\w\w\w)*?TGA/g) { # note the minimal *?
1632 print "Got a TGA stop codon at position ", pos $dna, "\n";
1637 Got a TGA stop codon at position 18
1638 Got a TGA stop codon at position 23
1640 Position 18 is good, but position 23 is bogus. What happened?
1642 The answer is that our regexp works well until we get past the last
1643 real match. Then the regexp will fail to match a synchronized C<TGA>
1644 and start stepping ahead one character position at a time, not what we
1645 want. The solution is to use C<\G> to anchor the match to the codon
1648 while ($dna =~ /\G(\w\w\w)*?TGA/g) {
1649 print "Got a TGA stop codon at position ", pos $dna, "\n";
1654 Got a TGA stop codon at position 18
1656 which is the correct answer. This example illustrates that it is
1657 important not only to match what is desired, but to reject what is not
1660 =head3 Search and replace
1662 Regular expressions also play a big role in I<search and replace>
1663 operations in Perl. Search and replace is accomplished with the
1664 C<s///> operator. The general form is
1665 C<s/regexp/replacement/modifiers>, with everything we know about
1666 regexps and modifiers applying in this case as well. The
1667 C<replacement> is a Perl double quoted string that replaces in the
1668 string whatever is matched with the C<regexp>. The operator C<=~> is
1669 also used here to associate a string with C<s///>. If matching
1670 against C<$_>, the S<C<$_ =~>> can be dropped. If there is a match,
1671 C<s///> returns the number of substitutions made, otherwise it returns
1672 false. Here are a few examples:
1674 $x = "Time to feed the cat!";
1675 $x =~ s/cat/hacker/; # $x contains "Time to feed the hacker!"
1676 if ($x =~ s/^(Time.*hacker)!$/$1 now!/) {
1677 $more_insistent = 1;
1679 $y = "'quoted words'";
1680 $y =~ s/^'(.*)'$/$1/; # strip single quotes,
1681 # $y contains "quoted words"
1683 In the last example, the whole string was matched, but only the part
1684 inside the single quotes was grouped. With the C<s///> operator, the
1685 matched variables C<$1>, C<$2>, etc. are immediately available for use
1686 in the replacement expression, so we use C<$1> to replace the quoted
1687 string with just what was quoted. With the global modifier, C<s///g>
1688 will search and replace all occurrences of the regexp in the string:
1690 $x = "I batted 4 for 4";
1691 $x =~ s/4/four/; # doesn't do it all:
1692 # $x contains "I batted four for 4"
1693 $x = "I batted 4 for 4";
1694 $x =~ s/4/four/g; # does it all:
1695 # $x contains "I batted four for four"
1697 If you prefer 'regex' over 'regexp' in this tutorial, you could use
1698 the following program to replace it:
1700 % cat > simple_replace
1703 $replacement = shift;
1705 s/$regexp/$replacement/go;
1710 % simple_replace regexp regex perlretut.pod
1712 In C<simple_replace> we used the C<s///g> modifier to replace all
1713 occurrences of the regexp on each line and the C<s///o> modifier to
1714 compile the regexp only once. As with C<simple_grep>, both the
1715 C<print> and the C<s/$regexp/$replacement/go> use C<$_> implicitly.
1717 A modifier available specifically to search and replace is the
1718 C<s///e> evaluation modifier. C<s///e> wraps an C<eval{...}> around
1719 the replacement string and the evaluated result is substituted for the
1720 matched substring. C<s///e> is useful if you need to do a bit of
1721 computation in the process of replacing text. This example counts
1722 character frequencies in a line:
1724 $x = "Bill the cat";
1725 $x =~ s/(.)/$chars{$1}++;$1/eg; # final $1 replaces char with itself
1726 print "frequency of '$_' is $chars{$_}\n"
1727 foreach (sort {$chars{$b} <=> $chars{$a}} keys %chars);
1731 frequency of ' ' is 2
1732 frequency of 't' is 2
1733 frequency of 'l' is 2
1734 frequency of 'B' is 1
1735 frequency of 'c' is 1
1736 frequency of 'e' is 1
1737 frequency of 'h' is 1
1738 frequency of 'i' is 1
1739 frequency of 'a' is 1
1741 As with the match C<m//> operator, C<s///> can use other delimiters,
1742 such as C<s!!!> and C<s{}{}>, and even C<s{}//>. If single quotes are
1743 used C<s'''>, then the regexp and replacement are treated as single
1744 quoted strings and there are no substitutions. C<s///> in list context
1745 returns the same thing as in scalar context, i.e., the number of
1748 =head3 The split function
1750 The C<split()> function is another place where a regexp is used.
1751 C<split /regexp/, string, limit> separates the C<string> operand into
1752 a list of substrings and returns that list. The regexp must be designed
1753 to match whatever constitutes the separators for the desired substrings.
1754 The C<limit>, if present, constrains splitting into no more than C<limit>
1755 number of strings. For example, to split a string into words, use
1757 $x = "Calvin and Hobbes";
1758 @words = split /\s+/, $x; # $word[0] = 'Calvin'
1760 # $word[2] = 'Hobbes'
1762 If the empty regexp C<//> is used, the regexp always matches and
1763 the string is split into individual characters. If the regexp has
1764 groupings, then the resulting list contains the matched substrings from the
1765 groupings as well. For instance,
1767 $x = "/usr/bin/perl";
1768 @dirs = split m!/!, $x; # $dirs[0] = ''
1772 @parts = split m!(/)!, $x; # $parts[0] = ''
1778 # $parts[6] = 'perl'
1780 Since the first character of $x matched the regexp, C<split> prepended
1781 an empty initial element to the list.
1783 If you have read this far, congratulations! You now have all the basic
1784 tools needed to use regular expressions to solve a wide range of text
1785 processing problems. If this is your first time through the tutorial,
1786 why not stop here and play around with regexps a while... S<Part 2>
1787 concerns the more esoteric aspects of regular expressions and those
1788 concepts certainly aren't needed right at the start.
1790 =head1 Part 2: Power tools
1792 OK, you know the basics of regexps and you want to know more. If
1793 matching regular expressions is analogous to a walk in the woods, then
1794 the tools discussed in Part 1 are analogous to topo maps and a
1795 compass, basic tools we use all the time. Most of the tools in part 2
1796 are analogous to flare guns and satellite phones. They aren't used
1797 too often on a hike, but when we are stuck, they can be invaluable.
1799 What follows are the more advanced, less used, or sometimes esoteric
1800 capabilities of Perl regexps. In Part 2, we will assume you are
1801 comfortable with the basics and concentrate on the new features.
1803 =head2 More on characters, strings, and character classes
1805 There are a number of escape sequences and character classes that we
1806 haven't covered yet.
1808 There are several escape sequences that convert characters or strings
1809 between upper and lower case, and they are also available within
1810 patterns. C<\l> and C<\u> convert the next character to lower or
1811 upper case, respectively:
1814 $string =~ /\u$x/; # matches 'Perl' in $string
1815 $x = "M(rs?|s)\\."; # note the double backslash
1816 $string =~ /\l$x/; # matches 'mr.', 'mrs.', and 'ms.',
1818 A C<\L> or C<\U> indicates a lasting conversion of case, until
1819 terminated by C<\E> or thrown over by another C<\U> or C<\L>:
1821 $x = "This word is in lower case:\L SHOUT\E";
1822 $x =~ /shout/; # matches
1823 $x = "I STILL KEYPUNCH CARDS FOR MY 360"
1824 $x =~ /\Ukeypunch/; # matches punch card string
1826 If there is no C<\E>, case is converted until the end of the
1827 string. The regexps C<\L\u$word> or C<\u\L$word> convert the first
1828 character of C<$word> to uppercase and the rest of the characters to
1831 Control characters can be escaped with C<\c>, so that a control-Z
1832 character would be matched with C<\cZ>. The escape sequence
1833 C<\Q>...C<\E> quotes, or protects most non-alphabetic characters. For
1836 $x = "\QThat !^*&%~& cat!";
1837 $x =~ /\Q!^*&%~&\E/; # check for rough language
1839 It does not protect C<$> or C<@>, so that variables can still be
1842 With the advent of 5.6.0, Perl regexps can handle more than just the
1843 standard ASCII character set. Perl now supports I<Unicode>, a standard
1844 for representing the alphabets from virtually all of the world's written
1845 languages, and a host of symbols. Perl's text strings are Unicode strings, so
1846 they can contain characters with a value (codepoint or character number) higher
1849 What does this mean for regexps? Well, regexp users don't need to know
1850 much about Perl's internal representation of strings. But they do need
1851 to know 1) how to represent Unicode characters in a regexp and 2) that
1852 a matching operation will treat the string to be searched as a sequence
1853 of characters, not bytes. The answer to 1) is that Unicode characters
1854 greater than C<chr(255)> are represented using the C<\x{hex}> notation,
1855 because the \0 octal and \x hex (without curly braces) don't go further
1858 /\x{263a}/; # match a Unicode smiley face :)
1860 B<NOTE>: In Perl 5.6.0 it used to be that one needed to say C<use
1861 utf8> to use any Unicode features. This is no more the case: for
1862 almost all Unicode processing, the explicit C<utf8> pragma is not
1863 needed. (The only case where it matters is if your Perl script is in
1864 Unicode and encoded in UTF-8, then an explicit C<use utf8> is needed.)
1866 Figuring out the hexadecimal sequence of a Unicode character you want
1867 or deciphering someone else's hexadecimal Unicode regexp is about as
1868 much fun as programming in machine code. So another way to specify
1869 Unicode characters is to use the I<named character>> escape
1870 sequence C<\N{name}>. C<name> is a name for the Unicode character, as
1871 specified in the Unicode standard. For instance, if we wanted to
1872 represent or match the astrological sign for the planet Mercury, we
1875 use charnames ":full"; # use named chars with Unicode full names
1876 $x = "abc\N{MERCURY}def";
1877 $x =~ /\N{MERCURY}/; # matches
1879 One can also use short names or restrict names to a certain alphabet:
1881 use charnames ':full';
1882 print "\N{GREEK SMALL LETTER SIGMA} is called sigma.\n";
1884 use charnames ":short";
1885 print "\N{greek:Sigma} is an upper-case sigma.\n";
1887 use charnames qw(greek);
1888 print "\N{sigma} is Greek sigma\n";
1890 A list of full names is found in the file NamesList.txt in the
1891 lib/perl5/X.X.X/unicore directory (where X.X.X is the perl
1892 version number as it is installed on your system).
1894 The answer to requirement 2), as of 5.6.0, is that a regexp uses Unicode
1895 characters. Internally, this is encoded to bytes using either UTF-8 or a
1896 native 8 bit encoding, depending on the history of the string, but
1897 conceptually it is a sequence of characters, not bytes. See
1898 L<perlunitut> for a tutorial about that.
1900 Let us now discuss Unicode character classes. Just as with Unicode
1901 characters, there are named Unicode character classes represented by the
1902 C<\p{name}> escape sequence. Closely associated is the C<\P{name}>
1903 character class, which is the negation of the C<\p{name}> class. For
1904 example, to match lower and uppercase characters,
1906 use charnames ":full"; # use named chars with Unicode full names
1908 $x =~ /^\p{IsUpper}/; # matches, uppercase char class
1909 $x =~ /^\P{IsUpper}/; # doesn't match, char class sans uppercase
1910 $x =~ /^\p{IsLower}/; # doesn't match, lowercase char class
1911 $x =~ /^\P{IsLower}/; # matches, char class sans lowercase
1913 Here is the association between some Perl named classes and the
1914 traditional Unicode classes:
1916 Perl class name Unicode class name or regular expression
1920 IsASCII $code <= 127
1922 IsBlank $code =~ /^(0020|0009)$/ || /^Z[^lp]/
1924 IsGraph /^([LMNPS]|Co)/
1926 IsPrint /^([LMNPS]|Co|Zs)/
1928 IsSpace /^Z/ || ($code =~ /^(0009|000A|000B|000C|000D)$/
1929 IsSpacePerl /^Z/ || ($code =~ /^(0009|000A|000C|000D|0085|2028|2029)$/
1931 IsWord /^[LMN]/ || $code eq "005F"
1932 IsXDigit $code =~ /^00(3[0-9]|[46][1-6])$/
1934 You can also use the official Unicode class names with the C<\p> and
1935 C<\P>, like C<\p{L}> for Unicode 'letters', or C<\p{Lu}> for uppercase
1936 letters, or C<\P{Nd}> for non-digits. If a C<name> is just one
1937 letter, the braces can be dropped. For instance, C<\pM> is the
1938 character class of Unicode 'marks', for example accent marks.
1939 For the full list see L<perlunicode>.
1941 The Unicode has also been separated into various sets of characters
1942 which you can test with C<\p{...}> (in) and C<\P{...}> (not in).
1943 To test whether a character is (or is not) an element of a script
1944 you would use the script name, for example C<\p{Latin}>, C<\p{Greek}>,
1945 or C<\P{Katakana}>. Other sets are the Unicode blocks, the names
1946 of which begin with "In". One such block is dedicated to mathematical
1947 operators, and its pattern formula is <C\p{InMathematicalOperators>}>.
1948 For the full list see L<perluniprops>.
1950 What we have described so far is the single form of the C<\p{...}> character
1951 classes. There is also a compound form which you may run into. These
1952 look like C<\p{name=value}> or C<\p{name:value}> (the equals sign and colon
1953 can be used interchangeably). These are more general than the single form,
1954 and in fact most of the single forms are just Perl-defined shortcuts for common
1955 compound forms. For example, the script examples in the previous paragraph
1956 could be written equivalently as C<\p{Script=Latin}>, C<\p{Script:Greek}>, and
1957 C<\P{script=katakana}> (case is irrelevant between the C<{}> braces). You may
1958 never have to use the compound forms, but sometimes it is necessary, and their
1959 use can make your code easier to understand.
1961 C<\X> is an abbreviation for a character class that comprises
1962 a Unicode I<extended grapheme cluster>. This represents a "logical character",
1963 what appears to be a single character, but may be represented internally by more
1964 than one. As an example, using the Unicode full names, e.g., S<C<A + COMBINING
1965 RING>> is a grapheme cluster with base character C<A> and combining character
1966 S<C<COMBINING RING>>, which translates in Danish to A with the circle atop it,
1967 as in the word Angstrom.
1969 For the full and latest information about Unicode see the latest
1970 Unicode standard, or the Unicode Consortium's website L<http://www.unicode.org>
1972 As if all those classes weren't enough, Perl also defines POSIX style
1973 character classes. These have the form C<[:name:]>, with C<name> the
1974 name of the POSIX class. The POSIX classes are C<alpha>, C<alnum>,
1975 C<ascii>, C<cntrl>, C<digit>, C<graph>, C<lower>, C<print>, C<punct>,
1976 C<space>, C<upper>, and C<xdigit>, and two extensions, C<word> (a Perl
1977 extension to match C<\w>), and C<blank> (a GNU extension). If C<utf8>
1978 is being used, then these classes are defined the same as their
1979 corresponding Perl Unicode classes: C<[:upper:]> is the same as
1980 C<\p{IsUpper}>, etc. The POSIX character classes, however, don't
1981 require using C<utf8>. The C<[:digit:]>, C<[:word:]>, and
1982 C<[:space:]> correspond to the familiar C<\d>, C<\w>, and C<\s>
1983 character classes. To negate a POSIX class, put a C<^> in front of
1984 the name, so that, e.g., C<[:^digit:]> corresponds to C<\D> and under
1985 C<utf8>, C<\P{IsDigit}>. The Unicode and POSIX character classes can
1986 be used just like C<\d>, with the exception that POSIX character
1987 classes can only be used inside of a character class:
1989 /\s+[abc[:digit:]xyz]\s*/; # match a,b,c,x,y,z, or a digit
1990 /^=item\s[[:digit:]]/; # match '=item',
1991 # followed by a space and a digit
1992 use charnames ":full";
1993 /\s+[abc\p{IsDigit}xyz]\s+/; # match a,b,c,x,y,z, or a digit
1994 /^=item\s\p{IsDigit}/; # match '=item',
1995 # followed by a space and a digit
1997 Whew! That is all the rest of the characters and character classes.
1999 =head2 Compiling and saving regular expressions
2001 In Part 1 we discussed the C<//o> modifier, which compiles a regexp
2002 just once. This suggests that a compiled regexp is some data structure
2003 that can be stored once and used again and again. The regexp quote
2004 C<qr//> does exactly that: C<qr/string/> compiles the C<string> as a
2005 regexp and transforms the result into a form that can be assigned to a
2008 $reg = qr/foo+bar?/; # reg contains a compiled regexp
2010 Then C<$reg> can be used as a regexp:
2013 $x =~ $reg; # matches, just like /foo+bar?/
2014 $x =~ /$reg/; # same thing, alternate form
2016 C<$reg> can also be interpolated into a larger regexp:
2018 $x =~ /(abc)?$reg/; # still matches
2020 As with the matching operator, the regexp quote can use different
2021 delimiters, e.g., C<qr!!>, C<qr{}> or C<qr~~>. Apostrophes
2022 as delimiters (C<qr''>) inhibit any interpolation.
2024 Pre-compiled regexps are useful for creating dynamic matches that
2025 don't need to be recompiled each time they are encountered. Using
2026 pre-compiled regexps, we write a C<grep_step> program which greps
2027 for a sequence of patterns, advancing to the next pattern as soon
2028 as one has been satisfied.
2032 # grep_step - match <number> regexps, one after the other
2033 # usage: multi_grep <number> regexp1 regexp2 ... file1 file2 ...
2036 $regexp[$_] = shift foreach (0..$number-1);
2037 @compiled = map qr/$_/, @regexp;
2038 while ($line = <>) {
2039 if ($line =~ /$compiled[0]/) {
2042 last unless @compiled;
2047 % grep_step 3 shift print last grep_step
2050 last unless @compiled;
2052 Storing pre-compiled regexps in an array C<@compiled> allows us to
2053 simply loop through the regexps without any recompilation, thus gaining
2054 flexibility without sacrificing speed.
2057 =head2 Composing regular expressions at runtime
2059 Backtracking is more efficient than repeated tries with different regular
2060 expressions. If there are several regular expressions and a match with
2061 any of them is acceptable, then it is possible to combine them into a set
2062 of alternatives. If the individual expressions are input data, this
2063 can be done by programming a join operation. We'll exploit this idea in
2064 an improved version of the C<simple_grep> program: a program that matches
2069 # multi_grep - match any of <number> regexps
2070 # usage: multi_grep <number> regexp1 regexp2 ... file1 file2 ...
2073 $regexp[$_] = shift foreach (0..$number-1);
2074 $pattern = join '|', @regexp;
2076 while ($line = <>) {
2077 print $line if $line =~ /$pattern/o;
2081 % multi_grep 2 shift for multi_grep
2083 $regexp[$_] = shift foreach (0..$number-1);
2085 Sometimes it is advantageous to construct a pattern from the I<input>
2086 that is to be analyzed and use the permissible values on the left
2087 hand side of the matching operations. As an example for this somewhat
2088 paradoxical situation, let's assume that our input contains a command
2089 verb which should match one out of a set of available command verbs,
2090 with the additional twist that commands may be abbreviated as long as
2091 the given string is unique. The program below demonstrates the basic
2096 $kwds = 'copy compare list print';
2097 while( $command = <> ){
2098 $command =~ s/^\s+|\s+$//g; # trim leading and trailing spaces
2099 if( ( @matches = $kwds =~ /\b$command\w*/g ) == 1 ){
2100 print "command: '@matches'\n";
2101 } elsif( @matches == 0 ){
2102 print "no such command: '$command'\n";
2104 print "not unique: '$command' (could be one of: @matches)\n";
2113 not unique: 'co' (could be one of: copy compare)
2115 no such command: 'printer'
2117 Rather than trying to match the input against the keywords, we match the
2118 combined set of keywords against the input. The pattern matching
2119 operation S<C<$kwds =~ /\b($command\w*)/g>> does several things at the
2120 same time. It makes sure that the given command begins where a keyword
2121 begins (C<\b>). It tolerates abbreviations due to the added C<\w*>. It
2122 tells us the number of matches (C<scalar @matches>) and all the keywords
2123 that were actually matched. You could hardly ask for more.
2125 =head2 Embedding comments and modifiers in a regular expression
2127 Starting with this section, we will be discussing Perl's set of
2128 I<extended patterns>. These are extensions to the traditional regular
2129 expression syntax that provide powerful new tools for pattern
2130 matching. We have already seen extensions in the form of the minimal
2131 matching constructs C<??>, C<*?>, C<+?>, C<{n,m}?>, and C<{n,}?>. The
2132 rest of the extensions below have the form C<(?char...)>, where the
2133 C<char> is a character that determines the type of extension.
2135 The first extension is an embedded comment C<(?#text)>. This embeds a
2136 comment into the regular expression without affecting its meaning. The
2137 comment should not have any closing parentheses in the text. An
2140 /(?# Match an integer:)[+-]?\d+/;
2142 This style of commenting has been largely superseded by the raw,
2143 freeform commenting that is allowed with the C<//x> modifier.
2145 The modifiers C<//i>, C<//m>, C<//s> and C<//x> (or any
2146 combination thereof) can also be embedded in
2147 a regexp using C<(?i)>, C<(?m)>, C<(?s)>, and C<(?x)>. For instance,
2149 /(?i)yes/; # match 'yes' case insensitively
2150 /yes/i; # same thing
2151 /(?x)( # freeform version of an integer regexp
2152 [+-]? # match an optional sign
2153 \d+ # match a sequence of digits
2157 Embedded modifiers can have two important advantages over the usual
2158 modifiers. Embedded modifiers allow a custom set of modifiers to
2159 I<each> regexp pattern. This is great for matching an array of regexps
2160 that must have different modifiers:
2162 $pattern[0] = '(?i)doctor';
2163 $pattern[1] = 'Johnson';
2166 foreach $patt (@pattern) {
2171 The second advantage is that embedded modifiers (except C<//p>, which
2172 modifies the entire regexp) only affect the regexp
2173 inside the group the embedded modifier is contained in. So grouping
2174 can be used to localize the modifier's effects:
2176 /Answer: ((?i)yes)/; # matches 'Answer: yes', 'Answer: YES', etc.
2178 Embedded modifiers can also turn off any modifiers already present
2179 by using, e.g., C<(?-i)>. Modifiers can also be combined into
2180 a single expression, e.g., C<(?s-i)> turns on single line mode and
2181 turns off case insensitivity.
2183 Embedded modifiers may also be added to a non-capturing grouping.
2184 C<(?i-m:regexp)> is a non-capturing grouping that matches C<regexp>
2185 case insensitively and turns off multi-line mode.
2188 =head2 Looking ahead and looking behind
2190 This section concerns the lookahead and lookbehind assertions. First,
2191 a little background.
2193 In Perl regular expressions, most regexp elements 'eat up' a certain
2194 amount of string when they match. For instance, the regexp element
2195 C<[abc}]> eats up one character of the string when it matches, in the
2196 sense that Perl moves to the next character position in the string
2197 after the match. There are some elements, however, that don't eat up
2198 characters (advance the character position) if they match. The examples
2199 we have seen so far are the anchors. The anchor C<^> matches the
2200 beginning of the line, but doesn't eat any characters. Similarly, the
2201 word boundary anchor C<\b> matches wherever a character matching C<\w>
2202 is next to a character that doesn't, but it doesn't eat up any
2203 characters itself. Anchors are examples of I<zero-width assertions>.
2204 Zero-width, because they consume
2205 no characters, and assertions, because they test some property of the
2206 string. In the context of our walk in the woods analogy to regexp
2207 matching, most regexp elements move us along a trail, but anchors have
2208 us stop a moment and check our surroundings. If the local environment
2209 checks out, we can proceed forward. But if the local environment
2210 doesn't satisfy us, we must backtrack.
2212 Checking the environment entails either looking ahead on the trail,
2213 looking behind, or both. C<^> looks behind, to see that there are no
2214 characters before. C<$> looks ahead, to see that there are no
2215 characters after. C<\b> looks both ahead and behind, to see if the
2216 characters on either side differ in their "word-ness".
2218 The lookahead and lookbehind assertions are generalizations of the
2219 anchor concept. Lookahead and lookbehind are zero-width assertions
2220 that let us specify which characters we want to test for. The
2221 lookahead assertion is denoted by C<(?=regexp)> and the lookbehind
2222 assertion is denoted by C<< (?<=fixed-regexp) >>. Some examples are
2224 $x = "I catch the housecat 'Tom-cat' with catnip";
2225 $x =~ /cat(?=\s)/; # matches 'cat' in 'housecat'
2226 @catwords = ($x =~ /(?<=\s)cat\w+/g); # matches,
2227 # $catwords[0] = 'catch'
2228 # $catwords[1] = 'catnip'
2229 $x =~ /\bcat\b/; # matches 'cat' in 'Tom-cat'
2230 $x =~ /(?<=\s)cat(?=\s)/; # doesn't match; no isolated 'cat' in
2233 Note that the parentheses in C<(?=regexp)> and C<< (?<=regexp) >> are
2234 non-capturing, since these are zero-width assertions. Thus in the
2235 second regexp, the substrings captured are those of the whole regexp
2236 itself. Lookahead C<(?=regexp)> can match arbitrary regexps, but
2237 lookbehind C<< (?<=fixed-regexp) >> only works for regexps of fixed
2238 width, i.e., a fixed number of characters long. Thus
2239 C<< (?<=(ab|bc)) >> is fine, but C<< (?<=(ab)*) >> is not. The
2240 negated versions of the lookahead and lookbehind assertions are
2241 denoted by C<(?!regexp)> and C<< (?<!fixed-regexp) >> respectively.
2242 They evaluate true if the regexps do I<not> match:
2245 $x =~ /foo(?!bar)/; # doesn't match, 'bar' follows 'foo'
2246 $x =~ /foo(?!baz)/; # matches, 'baz' doesn't follow 'foo'
2247 $x =~ /(?<!\s)foo/; # matches, there is no \s before 'foo'
2249 The C<\C> is unsupported in lookbehind, because the already
2250 treacherous definition of C<\C> would become even more so
2251 when going backwards.
2253 Here is an example where a string containing blank-separated words,
2254 numbers and single dashes is to be split into its components.
2255 Using C</\s+/> alone won't work, because spaces are not required between
2256 dashes, or a word or a dash. Additional places for a split are established
2257 by looking ahead and behind:
2259 $str = "one two - --6-8";
2260 @toks = split / \s+ # a run of spaces
2261 | (?<=\S) (?=-) # any non-space followed by '-'
2262 | (?<=-) (?=\S) # a '-' followed by any non-space
2263 /x, $str; # @toks = qw(one two - - - 6 - 8)
2266 =head2 Using independent subexpressions to prevent backtracking
2268 I<Independent subexpressions> are regular expressions, in the
2269 context of a larger regular expression, that function independently of
2270 the larger regular expression. That is, they consume as much or as
2271 little of the string as they wish without regard for the ability of
2272 the larger regexp to match. Independent subexpressions are represented
2273 by C<< (?>regexp) >>. We can illustrate their behavior by first
2274 considering an ordinary regexp:
2277 $x =~ /a*ab/; # matches
2279 This obviously matches, but in the process of matching, the
2280 subexpression C<a*> first grabbed the C<a>. Doing so, however,
2281 wouldn't allow the whole regexp to match, so after backtracking, C<a*>
2282 eventually gave back the C<a> and matched the empty string. Here, what
2283 C<a*> matched was I<dependent> on what the rest of the regexp matched.
2285 Contrast that with an independent subexpression:
2287 $x =~ /(?>a*)ab/; # doesn't match!
2289 The independent subexpression C<< (?>a*) >> doesn't care about the rest
2290 of the regexp, so it sees an C<a> and grabs it. Then the rest of the
2291 regexp C<ab> cannot match. Because C<< (?>a*) >> is independent, there
2292 is no backtracking and the independent subexpression does not give
2293 up its C<a>. Thus the match of the regexp as a whole fails. A similar
2294 behavior occurs with completely independent regexps:
2297 $x =~ /a*/g; # matches, eats an 'a'
2298 $x =~ /\Gab/g; # doesn't match, no 'a' available
2300 Here C<//g> and C<\G> create a 'tag team' handoff of the string from
2301 one regexp to the other. Regexps with an independent subexpression are
2302 much like this, with a handoff of the string to the independent
2303 subexpression, and a handoff of the string back to the enclosing
2306 The ability of an independent subexpression to prevent backtracking
2307 can be quite useful. Suppose we want to match a non-empty string
2308 enclosed in parentheses up to two levels deep. Then the following
2311 $x = "abc(de(fg)h"; # unbalanced parentheses
2312 $x =~ /\( ( [^()]+ | \([^()]*\) )+ \)/x;
2314 The regexp matches an open parenthesis, one or more copies of an
2315 alternation, and a close parenthesis. The alternation is two-way, with
2316 the first alternative C<[^()]+> matching a substring with no
2317 parentheses and the second alternative C<\([^()]*\)> matching a
2318 substring delimited by parentheses. The problem with this regexp is
2319 that it is pathological: it has nested indeterminate quantifiers
2320 of the form C<(a+|b)+>. We discussed in Part 1 how nested quantifiers
2321 like this could take an exponentially long time to execute if there
2322 was no match possible. To prevent the exponential blowup, we need to
2323 prevent useless backtracking at some point. This can be done by
2324 enclosing the inner quantifier as an independent subexpression:
2326 $x =~ /\( ( (?>[^()]+) | \([^()]*\) )+ \)/x;
2328 Here, C<< (?>[^()]+) >> breaks the degeneracy of string partitioning
2329 by gobbling up as much of the string as possible and keeping it. Then
2330 match failures fail much more quickly.
2333 =head2 Conditional expressions
2335 A I<conditional expression> is a form of if-then-else statement
2336 that allows one to choose which patterns are to be matched, based on
2337 some condition. There are two types of conditional expression:
2338 C<(?(condition)yes-regexp)> and
2339 C<(?(condition)yes-regexp|no-regexp)>. C<(?(condition)yes-regexp)> is
2340 like an S<C<'if () {}'>> statement in Perl. If the C<condition> is true,
2341 the C<yes-regexp> will be matched. If the C<condition> is false, the
2342 C<yes-regexp> will be skipped and Perl will move onto the next regexp
2343 element. The second form is like an S<C<'if () {} else {}'>> statement
2344 in Perl. If the C<condition> is true, the C<yes-regexp> will be
2345 matched, otherwise the C<no-regexp> will be matched.
2347 The C<condition> can have several forms. The first form is simply an
2348 integer in parentheses C<(integer)>. It is true if the corresponding
2349 backreference C<\integer> matched earlier in the regexp. The same
2350 thing can be done with a name associated with a capture buffer, written
2351 as C<< (<name>) >> or C<< ('name') >>. The second form is a bare
2352 zero width assertion C<(?...)>, either a lookahead, a lookbehind, or a
2353 code assertion (discussed in the next section). The third set of forms
2354 provides tests that return true if the expression is executed within
2355 a recursion (C<(R)>) or is being called from some capturing group,
2356 referenced either by number (C<(R1)>, C<(R2)>,...) or by name
2359 The integer or name form of the C<condition> allows us to choose,
2360 with more flexibility, what to match based on what matched earlier in the
2361 regexp. This searches for words of the form C<"$x$x"> or C<"$x$y$y$x">:
2363 % simple_grep '^(\w+)(\w+)?(?(2)\2\1|\1)$' /usr/dict/words
2373 The lookbehind C<condition> allows, along with backreferences,
2374 an earlier part of the match to influence a later part of the
2375 match. For instance,
2377 /[ATGC]+(?(?<=AA)G|C)$/;
2379 matches a DNA sequence such that it either ends in C<AAG>, or some
2380 other base pair combination and C<C>. Note that the form is
2381 C<< (?(?<=AA)G|C) >> and not C<< (?((?<=AA))G|C) >>; for the
2382 lookahead, lookbehind or code assertions, the parentheses around the
2383 conditional are not needed.
2386 =head2 Defining named patterns
2388 Some regular expressions use identical subpatterns in several places.
2389 Starting with Perl 5.10, it is possible to define named subpatterns in
2390 a section of the pattern so that they can be called up by name
2391 anywhere in the pattern. This syntactic pattern for this definition
2392 group is C<< (?(DEFINE)(?<name>pattern)...) >>. An insertion
2393 of a named pattern is written as C<(?&name)>.
2395 The example below illustrates this feature using the pattern for
2396 floating point numbers that was presented earlier on. The three
2397 subpatterns that are used more than once are the optional sign, the
2398 digit sequence for an integer and the decimal fraction. The DEFINE
2399 group at the end of the pattern contains their definition. Notice
2400 that the decimal fraction pattern is the first place where we can
2401 reuse the integer pattern.
2403 /^ (?&osg)\ * ( (?&int)(?&dec)? | (?&dec) )
2404 (?: [eE](?&osg)(?&int) )?
2407 (?<osg>[-+]?) # optional sign
2408 (?<int>\d++) # integer
2409 (?<dec>\.(?&int)) # decimal fraction
2413 =head2 Recursive patterns
2415 This feature (introduced in Perl 5.10) significantly extends the
2416 power of Perl's pattern matching. By referring to some other
2417 capture group anywhere in the pattern with the construct
2418 C<(?group-ref)>, the I<pattern> within the referenced group is used
2419 as an independent subpattern in place of the group reference itself.
2420 Because the group reference may be contained I<within> the group it
2421 refers to, it is now possible to apply pattern matching to tasks that
2422 hitherto required a recursive parser.
2424 To illustrate this feature, we'll design a pattern that matches if
2425 a string contains a palindrome. (This is a word or a sentence that,
2426 while ignoring spaces, interpunctuation and case, reads the same backwards
2427 as forwards. We begin by observing that the empty string or a string
2428 containing just one word character is a palindrome. Otherwise it must
2429 have a word character up front and the same at its end, with another
2430 palindrome in between.
2432 /(?: (\w) (?...Here be a palindrome...) \g{-1} | \w? )/x
2434 Adding C<\W*> at either end to eliminate what is to be ignored, we already
2435 have the full pattern:
2437 my $pp = qr/^(\W* (?: (\w) (?1) \g{-1} | \w? ) \W*)$/ix;
2438 for $s ( "saippuakauppias", "A man, a plan, a canal: Panama!" ){
2439 print "'$s' is a palindrome\n" if $s =~ /$pp/;
2442 In C<(?...)> both absolute and relative backreferences may be used.
2443 The entire pattern can be reinserted with C<(?R)> or C<(?0)>.
2444 If you prefer to name your buffers, you can use C<(?&name)> to
2445 recurse into that buffer.
2448 =head2 A bit of magic: executing Perl code in a regular expression
2450 Normally, regexps are a part of Perl expressions.
2451 I<Code evaluation> expressions turn that around by allowing
2452 arbitrary Perl code to be a part of a regexp. A code evaluation
2453 expression is denoted C<(?{code})>, with I<code> a string of Perl
2456 Be warned that this feature is considered experimental, and may be
2457 changed without notice.
2459 Code expressions are zero-width assertions, and the value they return
2460 depends on their environment. There are two possibilities: either the
2461 code expression is used as a conditional in a conditional expression
2462 C<(?(condition)...)>, or it is not. If the code expression is a
2463 conditional, the code is evaluated and the result (i.e., the result of
2464 the last statement) is used to determine truth or falsehood. If the
2465 code expression is not used as a conditional, the assertion always
2466 evaluates true and the result is put into the special variable
2467 C<$^R>. The variable C<$^R> can then be used in code expressions later
2468 in the regexp. Here are some silly examples:
2471 $x =~ /abc(?{print "Hi Mom!";})def/; # matches,
2473 $x =~ /aaa(?{print "Hi Mom!";})def/; # doesn't match,
2476 Pay careful attention to the next example:
2478 $x =~ /abc(?{print "Hi Mom!";})ddd/; # doesn't match,
2482 At first glance, you'd think that it shouldn't print, because obviously
2483 the C<ddd> isn't going to match the target string. But look at this
2486 $x =~ /abc(?{print "Hi Mom!";})[dD]dd/; # doesn't match,
2489 Hmm. What happened here? If you've been following along, you know that
2490 the above pattern should be effectively (almost) the same as the last one;
2491 enclosing the C<d> in a character class isn't going to change what it
2492 matches. So why does the first not print while the second one does?
2494 The answer lies in the optimizations the regex engine makes. In the first
2495 case, all the engine sees are plain old characters (aside from the
2496 C<?{}> construct). It's smart enough to realize that the string 'ddd'
2497 doesn't occur in our target string before actually running the pattern
2498 through. But in the second case, we've tricked it into thinking that our
2499 pattern is more complicated. It takes a look, sees our
2500 character class, and decides that it will have to actually run the
2501 pattern to determine whether or not it matches, and in the process of
2502 running it hits the print statement before it discovers that we don't
2505 To take a closer look at how the engine does optimizations, see the
2506 section L<"Pragmas and debugging"> below.
2508 More fun with C<?{}>:
2510 $x =~ /(?{print "Hi Mom!";})/; # matches,
2512 $x =~ /(?{$c = 1;})(?{print "$c";})/; # matches,
2514 $x =~ /(?{$c = 1;})(?{print "$^R";})/; # matches,
2517 The bit of magic mentioned in the section title occurs when the regexp
2518 backtracks in the process of searching for a match. If the regexp
2519 backtracks over a code expression and if the variables used within are
2520 localized using C<local>, the changes in the variables produced by the
2521 code expression are undone! Thus, if we wanted to count how many times
2522 a character got matched inside a group, we could use, e.g.,
2525 $count = 0; # initialize 'a' count
2526 $c = "bob"; # test if $c gets clobbered
2527 $x =~ /(?{local $c = 0;}) # initialize count
2529 (?{local $c = $c + 1;}) # increment count
2530 )* # do this any number of times,
2531 aa # but match 'aa' at the end
2532 (?{$count = $c;}) # copy local $c var into $count
2534 print "'a' count is $count, \$c variable is '$c'\n";
2538 'a' count is 2, $c variable is 'bob'
2540 If we replace the S<C< (?{local $c = $c + 1;})>> with
2541 S<C< (?{$c = $c + 1;})>>, the variable changes are I<not> undone
2542 during backtracking, and we get
2544 'a' count is 4, $c variable is 'bob'
2546 Note that only localized variable changes are undone. Other side
2547 effects of code expression execution are permanent. Thus
2550 $x =~ /(a(?{print "Yow\n";}))*aa/;
2559 The result C<$^R> is automatically localized, so that it will behave
2560 properly in the presence of backtracking.
2562 This example uses a code expression in a conditional to match a
2563 definite article, either 'the' in English or 'der|die|das' in German:
2565 $lang = 'DE'; # use German
2570 $lang eq 'EN'; # is the language English?
2572 the | # if so, then match 'the'
2573 (der|die|das) # else, match 'der|die|das'
2577 Note that the syntax here is C<(?(?{...})yes-regexp|no-regexp)>, not
2578 C<(?((?{...}))yes-regexp|no-regexp)>. In other words, in the case of a
2579 code expression, we don't need the extra parentheses around the
2582 If you try to use code expressions with interpolating variables, Perl
2587 /foo(?{ $bar })bar/; # compiles ok, $bar not interpolated
2588 /foo(?{ 1 })$bar/; # compile error!
2589 /foo${pat}bar/; # compile error!
2591 $pat = qr/(?{ $foo = 1 })/; # precompile code regexp
2592 /foo${pat}bar/; # compiles ok
2594 If a regexp has (1) code expressions and interpolating variables, or
2595 (2) a variable that interpolates a code expression, Perl treats the
2596 regexp as an error. If the code expression is precompiled into a
2597 variable, however, interpolating is ok. The question is, why is this
2600 The reason is that variable interpolation and code expressions
2601 together pose a security risk. The combination is dangerous because
2602 many programmers who write search engines often take user input and
2603 plug it directly into a regexp:
2605 $regexp = <>; # read user-supplied regexp
2606 $chomp $regexp; # get rid of possible newline
2607 $text =~ /$regexp/; # search $text for the $regexp
2609 If the C<$regexp> variable contains a code expression, the user could
2610 then execute arbitrary Perl code. For instance, some joker could
2611 search for S<C<system('rm -rf *');>> to erase your files. In this
2612 sense, the combination of interpolation and code expressions I<taints>
2613 your regexp. So by default, using both interpolation and code
2614 expressions in the same regexp is not allowed. If you're not
2615 concerned about malicious users, it is possible to bypass this
2616 security check by invoking S<C<use re 'eval'>>:
2618 use re 'eval'; # throw caution out the door
2621 /foo(?{ 1 })$bar/; # compiles ok
2622 /foo${pat}bar/; # compiles ok
2624 Another form of code expression is the I<pattern code expression>.
2625 The pattern code expression is like a regular code expression, except
2626 that the result of the code evaluation is treated as a regular
2627 expression and matched immediately. A simple example is
2632 $x =~ /(??{$char x $length})/x; # matches, there are 5 of 'a'
2635 This final example contains both ordinary and pattern code
2636 expressions. It detects whether a binary string C<1101010010001...> has a
2637 Fibonacci spacing 0,1,1,2,3,5,... of the C<1>'s:
2639 $x = "1101010010001000001";
2640 $z0 = ''; $z1 = '0'; # initial conditions
2641 print "It is a Fibonacci sequence\n"
2642 if $x =~ /^1 # match an initial '1'
2644 ((??{ $z0 })) # match some '0'
2646 (?{ $z0 = $z1; $z1 .= $^N; })
2647 )+ # repeat as needed
2648 $ # that is all there is
2650 printf "Largest sequence matched was %d\n", length($z1)-length($z0);
2652 Remember that C<$^N> is set to whatever was matched by the last
2653 completed capture group. This prints
2655 It is a Fibonacci sequence
2656 Largest sequence matched was 5
2658 Ha! Try that with your garden variety regexp package...
2660 Note that the variables C<$z0> and C<$z1> are not substituted when the
2661 regexp is compiled, as happens for ordinary variables outside a code
2662 expression. Rather, the code expressions are evaluated when Perl
2663 encounters them during the search for a match.
2665 The regexp without the C<//x> modifier is
2667 /^1(?:((??{ $z0 }))1(?{ $z0 = $z1; $z1 .= $^N; }))+$/
2669 which shows that spaces are still possible in the code parts. Nevertheless,
2670 when working with code and conditional expressions, the extended form of
2671 regexps is almost necessary in creating and debugging regexps.
2674 =head2 Backtracking control verbs
2676 Perl 5.10 introduced a number of control verbs intended to provide
2677 detailed control over the backtracking process, by directly influencing
2678 the regexp engine and by providing monitoring techniques. As all
2679 the features in this group are experimental and subject to change or
2680 removal in a future version of Perl, the interested reader is
2681 referred to L<perlre/"Special Backtracking Control Verbs"> for a
2682 detailed description.
2684 Below is just one example, illustrating the control verb C<(*FAIL)>,
2685 which may be abbreviated as C<(*F)>. If this is inserted in a regexp
2686 it will cause to fail, just like at some mismatch between the pattern
2687 and the string. Processing of the regexp continues like after any "normal"
2688 failure, so that, for instance, the next position in the string or another
2689 alternative will be tried. As failing to match doesn't preserve capture
2690 buffers or produce results, it may be necessary to use this in
2691 combination with embedded code.
2694 "supercalifragilisticexpialidoceous" =~
2695 /([aeiou])(?{ $count{$1}++; })(*FAIL)/oi;
2696 printf "%3d '%s'\n", $count{$_}, $_ for (sort keys %count);
2698 The pattern begins with a class matching a subset of letters. Whenever
2699 this matches, a statement like C<$count{'a'}++;> is executed, incrementing
2700 the letter's counter. Then C<(*FAIL)> does what it says, and
2701 the regexp engine proceeds according to the book: as long as the end of
2702 the string hasn't been reached, the position is advanced before looking
2703 for another vowel. Thus, match or no match makes no difference, and the
2704 regexp engine proceeds until the entire string has been inspected.
2705 (It's remarkable that an alternative solution using something like
2707 $count{lc($_)}++ for split('', "supercalifragilisticexpialidoceous");
2708 printf "%3d '%s'\n", $count2{$_}, $_ for ( qw{ a e i o u } );
2710 is considerably slower.)
2713 =head2 Pragmas and debugging
2715 Speaking of debugging, there are several pragmas available to control
2716 and debug regexps in Perl. We have already encountered one pragma in
2717 the previous section, S<C<use re 'eval';>>, that allows variable
2718 interpolation and code expressions to coexist in a regexp. The other
2723 @parts = ($tainted =~ /(\w+)\s+(\w+)/; # @parts is now tainted
2725 The C<taint> pragma causes any substrings from a match with a tainted
2726 variable to be tainted as well. This is not normally the case, as
2727 regexps are often used to extract the safe bits from a tainted
2728 variable. Use C<taint> when you are not extracting safe bits, but are
2729 performing some other processing. Both C<taint> and C<eval> pragmas
2730 are lexically scoped, which means they are in effect only until
2731 the end of the block enclosing the pragmas.
2734 /^(.*)$/s; # output debugging info
2736 use re 'debugcolor';
2737 /^(.*)$/s; # output debugging info in living color
2739 The global C<debug> and C<debugcolor> pragmas allow one to get
2740 detailed debugging info about regexp compilation and
2741 execution. C<debugcolor> is the same as debug, except the debugging
2742 information is displayed in color on terminals that can display
2743 termcap color sequences. Here is example output:
2745 % perl -e 'use re "debug"; "abc" =~ /a*b+c/;'
2746 Compiling REx `a*b+c'
2754 floating `bc' at 0..2147483647 (checking floating) minlen 2
2755 Guessing start of match, REx `a*b+c' against `abc'...
2756 Found floating substr `bc' at offset 1...
2757 Guessed: match at offset 0
2758 Matching REx `a*b+c' against `abc'
2759 Setting an EVAL scope, savestack=3
2760 0 <> <abc> | 1: STAR
2761 EXACT <a> can match 1 times out of 32767...
2762 Setting an EVAL scope, savestack=3
2763 1 <a> <bc> | 4: PLUS
2764 EXACT <b> can match 1 times out of 32767...
2765 Setting an EVAL scope, savestack=3
2766 2 <ab> <c> | 7: EXACT <c>
2769 Freeing REx: `a*b+c'
2771 If you have gotten this far into the tutorial, you can probably guess
2772 what the different parts of the debugging output tell you. The first
2775 Compiling REx `a*b+c'
2784 describes the compilation stage. C<STAR(4)> means that there is a
2785 starred object, in this case C<'a'>, and if it matches, goto line 4,
2786 i.e., C<PLUS(7)>. The middle lines describe some heuristics and
2787 optimizations performed before a match:
2789 floating `bc' at 0..2147483647 (checking floating) minlen 2
2790 Guessing start of match, REx `a*b+c' against `abc'...
2791 Found floating substr `bc' at offset 1...
2792 Guessed: match at offset 0
2794 Then the match is executed and the remaining lines describe the
2797 Matching REx `a*b+c' against `abc'
2798 Setting an EVAL scope, savestack=3
2799 0 <> <abc> | 1: STAR
2800 EXACT <a> can match 1 times out of 32767...
2801 Setting an EVAL scope, savestack=3
2802 1 <a> <bc> | 4: PLUS
2803 EXACT <b> can match 1 times out of 32767...
2804 Setting an EVAL scope, savestack=3
2805 2 <ab> <c> | 7: EXACT <c>
2808 Freeing REx: `a*b+c'
2810 Each step is of the form S<C<< n <x> <y> >>>, with C<< <x> >> the
2811 part of the string matched and C<< <y> >> the part not yet
2812 matched. The S<C<< | 1: STAR >>> says that Perl is at line number 1
2813 n the compilation list above. See
2814 L<perldebguts/"Debugging regular expressions"> for much more detail.
2816 An alternative method of debugging regexps is to embed C<print>
2817 statements within the regexp. This provides a blow-by-blow account of
2818 the backtracking in an alternation:
2820 "that this" =~ m@(?{print "Start at position ", pos, "\n";})
2830 (?{print "Done at position ", pos, "\n";})
2846 Code expressions, conditional expressions, and independent expressions
2847 are I<experimental>. Don't use them in production code. Yet.
2851 This is just a tutorial. For the full story on Perl regular
2852 expressions, see the L<perlre> regular expressions reference page.
2854 For more information on the matching C<m//> and substitution C<s///>
2855 operators, see L<perlop/"Regexp Quote-Like Operators">. For
2856 information on the C<split> operation, see L<perlfunc/split>.
2858 For an excellent all-around resource on the care and feeding of
2859 regular expressions, see the book I<Mastering Regular Expressions> by
2860 Jeffrey Friedl (published by O'Reilly, ISBN 1556592-257-3).
2862 =head1 AUTHOR AND COPYRIGHT
2864 Copyright (c) 2000 Mark Kvale
2865 All rights reserved.
2867 This document may be distributed under the same terms as Perl itself.
2869 =head2 Acknowledgments
2871 The inspiration for the stop codon DNA example came from the ZIP
2872 code example in chapter 7 of I<Mastering Regular Expressions>.
2874 The author would like to thank Jeff Pinyan, Andrew Johnson, Peter
2875 Haworth, Ronald J Kimball, and Joe Smith for all their helpful