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.
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 New in v5.22, L<C<use re 'strict'>|re/'strict' mode> applies stricter
53 rules than otherwise when compiling regular expression patterns. It can
54 find things that, while legal, may not be what you intended.
56 =head1 Part 1: The basics
58 =head2 Simple word matching
60 The simplest regexp is simply a word, or more generally, a string of
61 characters. A regexp consisting of a word matches any string that
64 "Hello World" =~ /World/; # matches
66 What is this Perl statement all about? C<"Hello World"> is a simple
67 double-quoted string. C<World> is the regular expression and the
68 C<//> enclosing C</World/> tells Perl to search a string for a match.
69 The operator C<=~> associates the string with the regexp match and
70 produces a true value if the regexp matched, or false if the regexp
71 did not match. In our case, C<World> matches the second word in
72 C<"Hello World">, so the expression is true. Expressions like this
73 are useful in conditionals:
75 if ("Hello World" =~ /World/) {
79 print "It doesn't match\n";
82 There are useful variations on this theme. The sense of the match can
83 be reversed by using the C<!~> operator:
85 if ("Hello World" !~ /World/) {
86 print "It doesn't match\n";
92 The literal string in the regexp can be replaced by a variable:
95 if ("Hello World" =~ /$greeting/) {
99 print "It doesn't match\n";
102 If you're matching against the special default variable C<$_>, the
103 C<$_ =~> part can be omitted:
107 print "It matches\n";
110 print "It doesn't match\n";
113 And finally, the C<//> default delimiters for a match can be changed
114 to arbitrary delimiters by putting an C<'m'> out front:
116 "Hello World" =~ m!World!; # matches, delimited by '!'
117 "Hello World" =~ m{World}; # matches, note the matching '{}'
118 "/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin',
119 # '/' becomes an ordinary char
121 C</World/>, C<m!World!>, and C<m{World}> all represent the
122 same thing. When, e.g., the quote (C<">) is used as a delimiter, the forward
123 slash C<'/'> becomes an ordinary character and can be used in this regexp
126 Let's consider how different regexps would match C<"Hello World">:
128 "Hello World" =~ /world/; # doesn't match
129 "Hello World" =~ /o W/; # matches
130 "Hello World" =~ /oW/; # doesn't match
131 "Hello World" =~ /World /; # doesn't match
133 The first regexp C<world> doesn't match because regexps are
134 case-sensitive. The second regexp matches because the substring
135 S<C<'o W'>> occurs in the string S<C<"Hello World">>. The space
136 character ' ' is treated like any other character in a regexp and is
137 needed to match in this case. The lack of a space character is the
138 reason the third regexp C<'oW'> doesn't match. The fourth regexp
139 C<'World '> doesn't match because there is a space at the end of the
140 regexp, but not at the end of the string. The lesson here is that
141 regexps must match a part of the string I<exactly> in order for the
142 statement to be true.
144 If a regexp matches in more than one place in the string, Perl will
145 always match at the earliest possible point in the string:
147 "Hello World" =~ /o/; # matches 'o' in 'Hello'
148 "That hat is red" =~ /hat/; # matches 'hat' in 'That'
150 With respect to character matching, there are a few more points you
151 need to know about. First of all, not all characters can be used 'as
152 is' in a match. Some characters, called I<metacharacters>, are reserved
153 for use in regexp notation. The metacharacters are
157 The significance of each of these will be explained
158 in the rest of the tutorial, but for now, it is important only to know
159 that a metacharacter can be matched by putting a backslash before it:
161 "2+2=4" =~ /2+2/; # doesn't match, + is a metacharacter
162 "2+2=4" =~ /2\+2/; # matches, \+ is treated like an ordinary +
163 "The interval is [0,1)." =~ /[0,1)./ # is a syntax error!
164 "The interval is [0,1)." =~ /\[0,1\)\./ # matches
165 "#!/usr/bin/perl" =~ /#!\/usr\/bin\/perl/; # matches
167 In the last regexp, the forward slash C<'/'> is also backslashed,
168 because it is used to delimit the regexp. This can lead to LTS
169 (leaning toothpick syndrome), however, and it is often more readable
170 to change delimiters.
172 "#!/usr/bin/perl" =~ m!#\!/usr/bin/perl!; # easier to read
174 The backslash character C<'\'> is a metacharacter itself and needs to
177 'C:\WIN32' =~ /C:\\WIN/; # matches
179 In addition to the metacharacters, there are some ASCII characters
180 which don't have printable character equivalents and are instead
181 represented by I<escape sequences>. Common examples are C<\t> for a
182 tab, C<\n> for a newline, C<\r> for a carriage return and C<\a> for a
183 bell (or alert). If your string is better thought of as a sequence of arbitrary
184 bytes, the octal escape sequence, e.g., C<\033>, or hexadecimal escape
185 sequence, e.g., C<\x1B> may be a more natural representation for your
186 bytes. Here are some examples of escapes:
188 "1000\t2000" =~ m(0\t2) # matches
189 "1000\n2000" =~ /0\n20/ # matches
190 "1000\t2000" =~ /\000\t2/ # doesn't match, "0" ne "\000"
191 "cat" =~ /\o{143}\x61\x74/ # matches in ASCII, but a weird way
194 If you've been around Perl a while, all this talk of escape sequences
195 may seem familiar. Similar escape sequences are used in double-quoted
196 strings and in fact the regexps in Perl are mostly treated as
197 double-quoted strings. This means that variables can be used in
198 regexps as well. Just like double-quoted strings, the values of the
199 variables in the regexp will be substituted in before the regexp is
200 evaluated for matching purposes. So we have:
203 'housecat' =~ /$foo/; # matches
204 'cathouse' =~ /cat$foo/; # matches
205 'housecat' =~ /${foo}cat/; # matches
207 So far, so good. With the knowledge above you can already perform
208 searches with just about any literal string regexp you can dream up.
209 Here is a I<very simple> emulation of the Unix grep program:
219 % chmod +x simple_grep
221 % simple_grep abba /usr/dict/words
232 This program is easy to understand. C<#!/usr/bin/perl> is the standard
233 way to invoke a perl program from the shell.
234 S<C<$regexp = shift;>> saves the first command line argument as the
235 regexp to be used, leaving the rest of the command line arguments to
236 be treated as files. S<C<< while (<>) >>> loops over all the lines in
237 all the files. For each line, S<C<print if /$regexp/;>> prints the
238 line if the regexp matches the line. In this line, both C<print> and
239 C</$regexp/> use the default variable C<$_> implicitly.
241 With all of the regexps above, if the regexp matched anywhere in the
242 string, it was considered a match. Sometimes, however, we'd like to
243 specify I<where> in the string the regexp should try to match. To do
244 this, we would use the I<anchor> metacharacters C<^> and C<$>. The
245 anchor C<^> means match at the beginning of the string and the anchor
246 C<$> means match at the end of the string, or before a newline at the
247 end of the string. Here is how they are used:
249 "housekeeper" =~ /keeper/; # matches
250 "housekeeper" =~ /^keeper/; # doesn't match
251 "housekeeper" =~ /keeper$/; # matches
252 "housekeeper\n" =~ /keeper$/; # matches
254 The second regexp doesn't match because C<^> constrains C<keeper> to
255 match only at the beginning of the string, but C<"housekeeper"> has
256 keeper starting in the middle. The third regexp does match, since the
257 C<$> constrains C<keeper> to match only at the end of the string.
259 When both C<^> and C<$> are used at the same time, the regexp has to
260 match both the beginning and the end of the string, i.e., the regexp
261 matches the whole string. Consider
263 "keeper" =~ /^keep$/; # doesn't match
264 "keeper" =~ /^keeper$/; # matches
265 "" =~ /^$/; # ^$ matches an empty string
267 The first regexp doesn't match because the string has more to it than
268 C<keep>. Since the second regexp is exactly the string, it
269 matches. Using both C<^> and C<$> in a regexp forces the complete
270 string to match, so it gives you complete control over which strings
271 match and which don't. Suppose you are looking for a fellow named
272 bert, off in a string by himself:
274 "dogbert" =~ /bert/; # matches, but not what you want
276 "dilbert" =~ /^bert/; # doesn't match, but ..
277 "bertram" =~ /^bert/; # matches, so still not good enough
279 "bertram" =~ /^bert$/; # doesn't match, good
280 "dilbert" =~ /^bert$/; # doesn't match, good
281 "bert" =~ /^bert$/; # matches, perfect
283 Of course, in the case of a literal string, one could just as easily
284 use the string comparison S<C<$string eq 'bert'>> and it would be
285 more efficient. The C<^...$> regexp really becomes useful when we
286 add in the more powerful regexp tools below.
288 =head2 Using character classes
290 Although one can already do quite a lot with the literal string
291 regexps above, we've only scratched the surface of regular expression
292 technology. In this and subsequent sections we will introduce regexp
293 concepts (and associated metacharacter notations) that will allow a
294 regexp to represent not just a single character sequence, but a I<whole
297 One such concept is that of a I<character class>. A character class
298 allows a set of possible characters, rather than just a single
299 character, to match at a particular point in a regexp. You can define
300 your own custom character classes. These
301 are denoted by brackets C<[...]>, with the set of characters
302 to be possibly matched inside. Here are some examples:
304 /cat/; # matches 'cat'
305 /[bcr]at/; # matches 'bat, 'cat', or 'rat'
306 /item[0123456789]/; # matches 'item0' or ... or 'item9'
307 "abc" =~ /[cab]/; # matches 'a'
309 In the last statement, even though C<'c'> is the first character in
310 the class, C<'a'> matches because the first character position in the
311 string is the earliest point at which the regexp can match.
313 /[yY][eE][sS]/; # match 'yes' in a case-insensitive way
314 # 'yes', 'Yes', 'YES', etc.
316 This regexp displays a common task: perform a case-insensitive
317 match. Perl provides a way of avoiding all those brackets by simply
318 appending an C<'i'> to the end of the match. Then C</[yY][eE][sS]/;>
319 can be rewritten as C</yes/i;>. The C<'i'> stands for
320 case-insensitive and is an example of a I<modifier> of the matching
321 operation. We will meet other modifiers later in the tutorial.
323 We saw in the section above that there were ordinary characters, which
324 represented themselves, and special characters, which needed a
325 backslash C<\> to represent themselves. The same is true in a
326 character class, but the sets of ordinary and special characters
327 inside a character class are different than those outside a character
328 class. The special characters for a character class are C<-]\^$> (and
329 the pattern delimiter, whatever it is).
330 C<]> is special because it denotes the end of a character class. C<$> is
331 special because it denotes a scalar variable. C<\> is special because
332 it is used in escape sequences, just like above. Here is how the
333 special characters C<]$\> are handled:
335 /[\]c]def/; # matches ']def' or 'cdef'
337 /[$x]at/; # matches 'bat', 'cat', or 'rat'
338 /[\$x]at/; # matches '$at' or 'xat'
339 /[\\$x]at/; # matches '\at', 'bat, 'cat', or 'rat'
341 The last two are a little tricky. In C<[\$x]>, the backslash protects
342 the dollar sign, so the character class has two members C<$> and C<x>.
343 In C<[\\$x]>, the backslash is protected, so C<$x> is treated as a
344 variable and substituted in double quote fashion.
346 The special character C<'-'> acts as a range operator within character
347 classes, so that a contiguous set of characters can be written as a
348 range. With ranges, the unwieldy C<[0123456789]> and C<[abc...xyz]>
349 become the svelte C<[0-9]> and C<[a-z]>. Some examples are
351 /item[0-9]/; # matches 'item0' or ... or 'item9'
352 /[0-9bx-z]aa/; # matches '0aa', ..., '9aa',
353 # 'baa', 'xaa', 'yaa', or 'zaa'
354 /[0-9a-fA-F]/; # matches a hexadecimal digit
355 /[0-9a-zA-Z_]/; # matches a "word" character,
356 # like those in a Perl variable name
358 If C<'-'> is the first or last character in a character class, it is
359 treated as an ordinary character; C<[-ab]>, C<[ab-]> and C<[a\-b]> are
362 The special character C<^> in the first position of a character class
363 denotes a I<negated character class>, which matches any character but
364 those in the brackets. Both C<[...]> and C<[^...]> must match a
365 character, or the match fails. Then
367 /[^a]at/; # doesn't match 'aat' or 'at', but matches
368 # all other 'bat', 'cat, '0at', '%at', etc.
369 /[^0-9]/; # matches a non-numeric character
370 /[a^]at/; # matches 'aat' or '^at'; here '^' is ordinary
372 Now, even C<[0-9]> can be a bother to write multiple times, so in the
373 interest of saving keystrokes and making regexps more readable, Perl
374 has several abbreviations for common character classes, as shown below.
375 Since the introduction of Unicode, unless the C<//a> modifier is in
376 effect, these character classes match more than just a few characters in
383 \d matches a digit, not just [0-9] but also digits from non-roman scripts
387 \s matches a whitespace character, the set [\ \t\r\n\f] and others
391 \w matches a word character (alphanumeric or _), not just [0-9a-zA-Z_]
392 but also digits and characters from non-roman scripts
396 \D is a negated \d; it represents any other character than a digit, or [^\d]
400 \S is a negated \s; it represents any non-whitespace character [^\s]
404 \W is a negated \w; it represents any non-word character [^\w]
408 The period '.' matches any character but "\n" (unless the modifier C<//s> is
409 in effect, as explained below).
413 \N, like the period, matches any character but "\n", but it does so
414 regardless of whether the modifier C<//s> is in effect.
418 The C<//a> modifier, available starting in Perl 5.14, is used to
419 restrict the matches of \d, \s, and \w to just those in the ASCII range.
420 It is useful to keep your program from being needlessly exposed to full
421 Unicode (and its accompanying security considerations) when all you want
422 is to process English-like text. (The "a" may be doubled, C<//aa>, to
423 provide even more restrictions, preventing case-insensitive matching of
424 ASCII with non-ASCII characters; otherwise a Unicode "Kelvin Sign"
425 would caselessly match a "k" or "K".)
427 The C<\d\s\w\D\S\W> abbreviations can be used both inside and outside
428 of bracketed character classes. Here are some in use:
430 /\d\d:\d\d:\d\d/; # matches a hh:mm:ss time format
431 /[\d\s]/; # matches any digit or whitespace character
432 /\w\W\w/; # matches a word char, followed by a
433 # non-word char, followed by a word char
434 /..rt/; # matches any two chars, followed by 'rt'
435 /end\./; # matches 'end.'
436 /end[.]/; # same thing, matches 'end.'
438 Because a period is a metacharacter, it needs to be escaped to match
439 as an ordinary period. Because, for example, C<\d> and C<\w> are sets
440 of characters, it is incorrect to think of C<[^\d\w]> as C<[\D\W]>; in
441 fact C<[^\d\w]> is the same as C<[^\w]>, which is the same as
442 C<[\W]>. Think DeMorgan's laws.
444 In actuality, the period and C<\d\s\w\D\S\W> abbreviations are
445 themselves types of character classes, so the ones surrounded by
446 brackets are just one type of character class. When we need to make a
447 distinction, we refer to them as "bracketed character classes."
449 An anchor useful in basic regexps is the I<word anchor>
450 C<\b>. This matches a boundary between a word character and a non-word
451 character C<\w\W> or C<\W\w>:
453 $x = "Housecat catenates house and cat";
454 $x =~ /cat/; # matches cat in 'housecat'
455 $x =~ /\bcat/; # matches cat in 'catenates'
456 $x =~ /cat\b/; # matches cat in 'housecat'
457 $x =~ /\bcat\b/; # matches 'cat' at end of string
459 Note in the last example, the end of the string is considered a word
462 For natural language processing (so that, for example, apostrophes are
463 included in words), use instead C<\b{wb}>
465 "don't" =~ / .+? \b{wb} /x; # matches the whole string
467 You might wonder why C<'.'> matches everything but C<"\n"> - why not
468 every character? The reason is that often one is matching against
469 lines and would like to ignore the newline characters. For instance,
470 while the string C<"\n"> represents one line, we would like to think
473 "" =~ /^$/; # matches
474 "\n" =~ /^$/; # matches, $ anchors before "\n"
476 "" =~ /./; # doesn't match; it needs a char
477 "" =~ /^.$/; # doesn't match; it needs a char
478 "\n" =~ /^.$/; # doesn't match; it needs a char other than "\n"
479 "a" =~ /^.$/; # matches
480 "a\n" =~ /^.$/; # matches, $ anchors before "\n"
482 This behavior is convenient, because we usually want to ignore
483 newlines when we count and match characters in a line. Sometimes,
484 however, we want to keep track of newlines. We might even want C<^>
485 and C<$> to anchor at the beginning and end of lines within the
486 string, rather than just the beginning and end of the string. Perl
487 allows us to choose between ignoring and paying attention to newlines
488 by using the C<//s> and C<//m> modifiers. C<//s> and C<//m> stand for
489 single line and multi-line and they determine whether a string is to
490 be treated as one continuous string, or as a set of lines. The two
491 modifiers affect two aspects of how the regexp is interpreted: 1) how
492 the C<'.'> character class is defined, and 2) where the anchors C<^>
493 and C<$> are able to match. Here are the four possible combinations:
499 no modifiers (//): Default behavior. C<'.'> matches any character
500 except C<"\n">. C<^> matches only at the beginning of the string and
501 C<$> matches only at the end or before a newline at the end.
505 s modifier (//s): Treat string as a single long line. C<'.'> matches
506 any character, even C<"\n">. C<^> matches only at the beginning of
507 the string and C<$> matches only at the end or before a newline at the
512 m modifier (//m): Treat string as a set of multiple lines. C<'.'>
513 matches any character except C<"\n">. C<^> and C<$> are able to match
514 at the start or end of I<any> line within the string.
518 both s and m modifiers (//sm): Treat string as a single long line, but
519 detect multiple lines. C<'.'> matches any character, even
520 C<"\n">. C<^> and C<$>, however, are able to match at the start or end
521 of I<any> line within the string.
525 Here are examples of C<//s> and C<//m> in action:
527 $x = "There once was a girl\nWho programmed in Perl\n";
529 $x =~ /^Who/; # doesn't match, "Who" not at start of string
530 $x =~ /^Who/s; # doesn't match, "Who" not at start of string
531 $x =~ /^Who/m; # matches, "Who" at start of second line
532 $x =~ /^Who/sm; # matches, "Who" at start of second line
534 $x =~ /girl.Who/; # doesn't match, "." doesn't match "\n"
535 $x =~ /girl.Who/s; # matches, "." matches "\n"
536 $x =~ /girl.Who/m; # doesn't match, "." doesn't match "\n"
537 $x =~ /girl.Who/sm; # matches, "." matches "\n"
539 Most of the time, the default behavior is what is wanted, but C<//s> and
540 C<//m> are occasionally very useful. If C<//m> is being used, the start
541 of the string can still be matched with C<\A> and the end of the string
542 can still be matched with the anchors C<\Z> (matches both the end and
543 the newline before, like C<$>), and C<\z> (matches only the end):
545 $x =~ /^Who/m; # matches, "Who" at start of second line
546 $x =~ /\AWho/m; # doesn't match, "Who" is not at start of string
548 $x =~ /girl$/m; # matches, "girl" at end of first line
549 $x =~ /girl\Z/m; # doesn't match, "girl" is not at end of string
551 $x =~ /Perl\Z/m; # matches, "Perl" is at newline before end
552 $x =~ /Perl\z/m; # doesn't match, "Perl" is not at end of string
554 We now know how to create choices among classes of characters in a
555 regexp. What about choices among words or character strings? Such
556 choices are described in the next section.
558 =head2 Matching this or that
560 Sometimes we would like our regexp to be able to match different
561 possible words or character strings. This is accomplished by using
562 the I<alternation> metacharacter C<|>. To match C<dog> or C<cat>, we
563 form the regexp C<dog|cat>. As before, Perl will try to match the
564 regexp at the earliest possible point in the string. At each
565 character position, Perl will first try to match the first
566 alternative, C<dog>. If C<dog> doesn't match, Perl will then try the
567 next alternative, C<cat>. If C<cat> doesn't match either, then the
568 match fails and Perl moves to the next position in the string. Some
571 "cats and dogs" =~ /cat|dog|bird/; # matches "cat"
572 "cats and dogs" =~ /dog|cat|bird/; # matches "cat"
574 Even though C<dog> is the first alternative in the second regexp,
575 C<cat> is able to match earlier in the string.
577 "cats" =~ /c|ca|cat|cats/; # matches "c"
578 "cats" =~ /cats|cat|ca|c/; # matches "cats"
580 Here, all the alternatives match at the first string position, so the
581 first alternative is the one that matches. If some of the
582 alternatives are truncations of the others, put the longest ones first
583 to give them a chance to match.
585 "cab" =~ /a|b|c/ # matches "c"
588 The last example points out that character classes are like
589 alternations of characters. At a given character position, the first
590 alternative that allows the regexp match to succeed will be the one
593 =head2 Grouping things and hierarchical matching
595 Alternation allows a regexp to choose among alternatives, but by
596 itself it is unsatisfying. The reason is that each alternative is a whole
597 regexp, but sometime we want alternatives for just part of a
598 regexp. For instance, suppose we want to search for housecats or
599 housekeepers. The regexp C<housecat|housekeeper> fits the bill, but is
600 inefficient because we had to type C<house> twice. It would be nice to
601 have parts of the regexp be constant, like C<house>, and some
602 parts have alternatives, like C<cat|keeper>.
604 The I<grouping> metacharacters C<()> solve this problem. Grouping
605 allows parts of a regexp to be treated as a single unit. Parts of a
606 regexp are grouped by enclosing them in parentheses. Thus we could solve
607 the C<housecat|housekeeper> by forming the regexp as
608 C<house(cat|keeper)>. The regexp C<house(cat|keeper)> means match
609 C<house> followed by either C<cat> or C<keeper>. Some more examples
612 /(a|b)b/; # matches 'ab' or 'bb'
613 /(ac|b)b/; # matches 'acb' or 'bb'
614 /(^a|b)c/; # matches 'ac' at start of string or 'bc' anywhere
615 /(a|[bc])d/; # matches 'ad', 'bd', or 'cd'
617 /house(cat|)/; # matches either 'housecat' or 'house'
618 /house(cat(s|)|)/; # matches either 'housecats' or 'housecat' or
619 # 'house'. Note groups can be nested.
621 /(19|20|)\d\d/; # match years 19xx, 20xx, or the Y2K problem, xx
622 "20" =~ /(19|20|)\d\d/; # matches the null alternative '()\d\d',
623 # because '20\d\d' can't match
625 Alternations behave the same way in groups as out of them: at a given
626 string position, the leftmost alternative that allows the regexp to
627 match is taken. So in the last example at the first string position,
628 C<"20"> matches the second alternative, but there is nothing left over
629 to match the next two digits C<\d\d>. So Perl moves on to the next
630 alternative, which is the null alternative and that works, since
631 C<"20"> is two digits.
633 The process of trying one alternative, seeing if it matches, and
634 moving on to the next alternative, while going back in the string
635 from where the previous alternative was tried, if it doesn't, is called
636 I<backtracking>. The term 'backtracking' comes from the idea that
637 matching a regexp is like a walk in the woods. Successfully matching
638 a regexp is like arriving at a destination. There are many possible
639 trailheads, one for each string position, and each one is tried in
640 order, left to right. From each trailhead there may be many paths,
641 some of which get you there, and some which are dead ends. When you
642 walk along a trail and hit a dead end, you have to backtrack along the
643 trail to an earlier point to try another trail. If you hit your
644 destination, you stop immediately and forget about trying all the
645 other trails. You are persistent, and only if you have tried all the
646 trails from all the trailheads and not arrived at your destination, do
647 you declare failure. To be concrete, here is a step-by-step analysis
648 of what Perl does when it tries to match the regexp
650 "abcde" =~ /(abd|abc)(df|d|de)/;
656 Start with the first letter in the string 'a'.
660 Try the first alternative in the first group 'abd'.
664 Match 'a' followed by 'b'. So far so good.
668 'd' in the regexp doesn't match 'c' in the string - a dead
669 end. So backtrack two characters and pick the second alternative in
670 the first group 'abc'.
674 Match 'a' followed by 'b' followed by 'c'. We are on a roll
675 and have satisfied the first group. Set $1 to 'abc'.
679 Move on to the second group and pick the first alternative
688 'f' in the regexp doesn't match 'e' in the string, so a dead
689 end. Backtrack one character and pick the second alternative in the
694 'd' matches. The second grouping is satisfied, so set $2 to
699 We are at the end of the regexp, so we are done! We have
700 matched 'abcd' out of the string "abcde".
704 There are a couple of things to note about this analysis. First, the
705 third alternative in the second group 'de' also allows a match, but we
706 stopped before we got to it - at a given character position, leftmost
707 wins. Second, we were able to get a match at the first character
708 position of the string 'a'. If there were no matches at the first
709 position, Perl would move to the second character position 'b' and
710 attempt the match all over again. Only when all possible paths at all
711 possible character positions have been exhausted does Perl give
712 up and declare S<C<$string =~ /(abd|abc)(df|d|de)/;>> to be false.
714 Even with all this work, regexp matching happens remarkably fast. To
715 speed things up, Perl compiles the regexp into a compact sequence of
716 opcodes that can often fit inside a processor cache. When the code is
717 executed, these opcodes can then run at full throttle and search very
720 =head2 Extracting matches
722 The grouping metacharacters C<()> also serve another completely
723 different function: they allow the extraction of the parts of a string
724 that matched. This is very useful to find out what matched and for
725 text processing in general. For each grouping, the part that matched
726 inside goes into the special variables C<$1>, C<$2>, etc. They can be
727 used just as ordinary variables:
729 # extract hours, minutes, seconds
730 if ($time =~ /(\d\d):(\d\d):(\d\d)/) { # match hh:mm:ss format
736 Now, we know that in scalar context,
737 S<C<$time =~ /(\d\d):(\d\d):(\d\d)/>> returns a true or false
738 value. In list context, however, it returns the list of matched values
739 C<($1,$2,$3)>. So we could write the code more compactly as
741 # extract hours, minutes, seconds
742 ($hours, $minutes, $second) = ($time =~ /(\d\d):(\d\d):(\d\d)/);
744 If the groupings in a regexp are nested, C<$1> gets the group with the
745 leftmost opening parenthesis, C<$2> the next opening parenthesis,
746 etc. Here is a regexp with nested groups:
748 /(ab(cd|ef)((gi)|j))/;
751 If this regexp matches, C<$1> contains a string starting with
752 C<'ab'>, C<$2> is either set to C<'cd'> or C<'ef'>, C<$3> equals either
753 C<'gi'> or C<'j'>, and C<$4> is either set to C<'gi'>, just like C<$3>,
754 or it remains undefined.
756 For convenience, Perl sets C<$+> to the string held by the highest numbered
757 C<$1>, C<$2>,... that got assigned (and, somewhat related, C<$^N> to the
758 value of the C<$1>, C<$2>,... most-recently assigned; i.e. the C<$1>,
759 C<$2>,... associated with the rightmost closing parenthesis used in the
763 =head2 Backreferences
765 Closely associated with the matching variables C<$1>, C<$2>, ... are
766 the I<backreferences> C<\g1>, C<\g2>,... Backreferences are simply
767 matching variables that can be used I<inside> a regexp. This is a
768 really nice feature; what matches later in a regexp is made to depend on
769 what matched earlier in the regexp. Suppose we wanted to look
770 for doubled words in a text, like 'the the'. The following regexp finds
771 all 3-letter doubles with a space in between:
775 The grouping assigns a value to \g1, so that the same 3-letter sequence
776 is used for both parts.
778 A similar task is to find words consisting of two identical parts:
780 % simple_grep '^(\w\w\w\w|\w\w\w|\w\w|\w)\g1$' /usr/dict/words
788 The regexp has a single grouping which considers 4-letter
789 combinations, then 3-letter combinations, etc., and uses C<\g1> to look for
790 a repeat. Although C<$1> and C<\g1> represent the same thing, care should be
791 taken to use matched variables C<$1>, C<$2>,... only I<outside> a regexp
792 and backreferences C<\g1>, C<\g2>,... only I<inside> a regexp; not doing
793 so may lead to surprising and unsatisfactory results.
796 =head2 Relative backreferences
798 Counting the opening parentheses to get the correct number for a
799 backreference is error-prone as soon as there is more than one
800 capturing group. A more convenient technique became available
801 with Perl 5.10: relative backreferences. To refer to the immediately
802 preceding capture group one now may write C<\g{-1}>, the next but
803 last is available via C<\g{-2}>, and so on.
805 Another good reason in addition to readability and maintainability
806 for using relative backreferences is illustrated by the following example,
807 where a simple pattern for matching peculiar strings is used:
809 $a99a = '([a-z])(\d)\g2\g1'; # matches a11a, g22g, x33x, etc.
811 Now that we have this pattern stored as a handy string, we might feel
812 tempted to use it as a part of some other pattern:
815 if ($line =~ /^(\w+)=$a99a$/){ # unexpected behavior!
816 print "$1 is valid\n";
818 print "bad line: '$line'\n";
821 But this doesn't match, at least not the way one might expect. Only
822 after inserting the interpolated C<$a99a> and looking at the resulting
823 full text of the regexp is it obvious that the backreferences have
824 backfired. The subexpression C<(\w+)> has snatched number 1 and
825 demoted the groups in C<$a99a> by one rank. This can be avoided by
826 using relative backreferences:
828 $a99a = '([a-z])(\d)\g{-1}\g{-2}'; # safe for being interpolated
831 =head2 Named backreferences
833 Perl 5.10 also introduced named capture groups and named backreferences.
834 To attach a name to a capturing group, you write either
835 C<< (?<name>...) >> or C<< (?'name'...) >>. The backreference may
836 then be written as C<\g{name}>. It is permissible to attach the
837 same name to more than one group, but then only the leftmost one of the
838 eponymous set can be referenced. Outside of the pattern a named
839 capture group is accessible through the C<%+> hash.
841 Assuming that we have to match calendar dates which may be given in one
842 of the three formats yyyy-mm-dd, mm/dd/yyyy or dd.mm.yyyy, we can write
843 three suitable patterns where we use 'd', 'm' and 'y' respectively as the
844 names of the groups capturing the pertaining components of a date. The
845 matching operation combines the three patterns as alternatives:
847 $fmt1 = '(?<y>\d\d\d\d)-(?<m>\d\d)-(?<d>\d\d)';
848 $fmt2 = '(?<m>\d\d)/(?<d>\d\d)/(?<y>\d\d\d\d)';
849 $fmt3 = '(?<d>\d\d)\.(?<m>\d\d)\.(?<y>\d\d\d\d)';
850 for my $d qw( 2006-10-21 15.01.2007 10/31/2005 ){
851 if ( $d =~ m{$fmt1|$fmt2|$fmt3} ){
852 print "day=$+{d} month=$+{m} year=$+{y}\n";
856 If any of the alternatives matches, the hash C<%+> is bound to contain the
857 three key-value pairs.
860 =head2 Alternative capture group numbering
862 Yet another capturing group numbering technique (also as from Perl 5.10)
863 deals with the problem of referring to groups within a set of alternatives.
864 Consider a pattern for matching a time of the day, civil or military style:
866 if ( $time =~ /(\d\d|\d):(\d\d)|(\d\d)(\d\d)/ ){
867 # process hour and minute
870 Processing the results requires an additional if statement to determine
871 whether C<$1> and C<$2> or C<$3> and C<$4> contain the goodies. It would
872 be easier if we could use group numbers 1 and 2 in second alternative as
873 well, and this is exactly what the parenthesized construct C<(?|...)>,
874 set around an alternative achieves. Here is an extended version of the
877 if($time =~ /(?|(\d\d|\d):(\d\d)|(\d\d)(\d\d))\s+([A-Z][A-Z][A-Z])/){
878 print "hour=$1 minute=$2 zone=$3\n";
881 Within the alternative numbering group, group numbers start at the same
882 position for each alternative. After the group, numbering continues
883 with one higher than the maximum reached across all the alternatives.
885 =head2 Position information
887 In addition to what was matched, Perl also provides the
888 positions of what was matched as contents of the C<@-> and C<@+>
889 arrays. C<$-[0]> is the position of the start of the entire match and
890 C<$+[0]> is the position of the end. Similarly, C<$-[n]> is the
891 position of the start of the C<$n> match and C<$+[n]> is the position
892 of the end. If C<$n> is undefined, so are C<$-[n]> and C<$+[n]>. Then
895 $x = "Mmm...donut, thought Homer";
896 $x =~ /^(Mmm|Yech)\.\.\.(donut|peas)/; # matches
897 foreach $exp (1..$#-) {
898 print "Match $exp: '${$exp}' at position ($-[$exp],$+[$exp])\n";
903 Match 1: 'Mmm' at position (0,3)
904 Match 2: 'donut' at position (6,11)
906 Even if there are no groupings in a regexp, it is still possible to
907 find out what exactly matched in a string. If you use them, Perl
908 will set C<$`> to the part of the string before the match, will set C<$&>
909 to the part of the string that matched, and will set C<$'> to the part
910 of the string after the match. An example:
912 $x = "the cat caught the mouse";
913 $x =~ /cat/; # $` = 'the ', $& = 'cat', $' = ' caught the mouse'
914 $x =~ /the/; # $` = '', $& = 'the', $' = ' cat caught the mouse'
916 In the second match, C<$`> equals C<''> because the regexp matched at the
917 first character position in the string and stopped; it never saw the
920 If your code is to run on Perl versions earlier than
921 5.20, it is worthwhile to note that using C<$`> and C<$'>
922 slows down regexp matching quite a bit, while C<$&> slows it down to a
923 lesser extent, because if they are used in one regexp in a program,
924 they are generated for I<all> regexps in the program. So if raw
925 performance is a goal of your application, they should be avoided.
926 If you need to extract the corresponding substrings, use C<@-> and
929 $` is the same as substr( $x, 0, $-[0] )
930 $& is the same as substr( $x, $-[0], $+[0]-$-[0] )
931 $' is the same as substr( $x, $+[0] )
933 As of Perl 5.10, the C<${^PREMATCH}>, C<${^MATCH}> and C<${^POSTMATCH}>
934 variables may be used. These are only set if the C</p> modifier is
935 present. Consequently they do not penalize the rest of the program. In
936 Perl 5.20, C<${^PREMATCH}>, C<${^MATCH}> and C<${^POSTMATCH}> are available
937 whether the C</p> has been used or not (the modifier is ignored), and
938 C<$`>, C<$'> and C<$&> do not cause any speed difference.
940 =head2 Non-capturing groupings
942 A group that is required to bundle a set of alternatives may or may not be
943 useful as a capturing group. If it isn't, it just creates a superfluous
944 addition to the set of available capture group values, inside as well as
945 outside the regexp. Non-capturing groupings, denoted by C<(?:regexp)>,
946 still allow the regexp to be treated as a single unit, but don't establish
947 a capturing group at the same time. Both capturing and non-capturing
948 groupings are allowed to co-exist in the same regexp. Because there is
949 no extraction, non-capturing groupings are faster than capturing
950 groupings. Non-capturing groupings are also handy for choosing exactly
951 which parts of a regexp are to be extracted to matching variables:
953 # match a number, $1-$4 are set, but we only want $1
954 /([+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)/;
956 # match a number faster , only $1 is set
957 /([+-]?\ *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)/;
959 # match a number, get $1 = whole number, $2 = exponent
960 /([+-]?\ *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE]([+-]?\d+))?)/;
962 Non-capturing groupings are also useful for removing nuisance
963 elements gathered from a split operation where parentheses are
964 required for some reason:
967 @num = split /(a|b)+/, $x; # @num = ('12','a','34','a','5')
968 @num = split /(?:a|b)+/, $x; # @num = ('12','34','5')
970 In Perl 5.22 and later, all groups within a regexp can be set to
971 non-capturing by using the new C</n> flag:
973 "hello" =~ /(hi|hello)/n; # $1 is not set!
975 See L<perlre/"n"> for more information.
977 =head2 Matching repetitions
979 The examples in the previous section display an annoying weakness. We
980 were only matching 3-letter words, or chunks of words of 4 letters or
981 less. We'd like to be able to match words or, more generally, strings
982 of any length, without writing out tedious alternatives like
983 C<\w\w\w\w|\w\w\w|\w\w|\w>.
985 This is exactly the problem the I<quantifier> metacharacters C<?>,
986 C<*>, C<+>, and C<{}> were created for. They allow us to delimit the
987 number of repeats for a portion of a regexp we consider to be a
988 match. Quantifiers are put immediately after the character, character
989 class, or grouping that we want to specify. They have the following
996 C<a?> means: match 'a' 1 or 0 times
1000 C<a*> means: match 'a' 0 or more times, i.e., any number of times
1004 C<a+> means: match 'a' 1 or more times, i.e., at least once
1008 C<a{n,m}> means: match at least C<n> times, but not more than C<m>
1013 C<a{n,}> means: match at least C<n> or more times
1017 C<a{n}> means: match exactly C<n> times
1021 Here are some examples:
1023 /[a-z]+\s+\d*/; # match a lowercase word, at least one space, and
1024 # any number of digits
1025 /(\w+)\s+\g1/; # match doubled words of arbitrary length
1026 /y(es)?/i; # matches 'y', 'Y', or a case-insensitive 'yes'
1027 $year =~ /^\d{2,4}$/; # make sure year is at least 2 but not more
1029 $year =~ /^\d{4}$|^\d{2}$/; # better match; throw out 3-digit dates
1030 $year =~ /^\d{2}(\d{2})?$/; # same thing written differently.
1031 # However, this captures the last two
1032 # digits in $1 and the other does not.
1034 % simple_grep '^(\w+)\g1$' /usr/dict/words # isn't this easier?
1042 For all of these quantifiers, Perl will try to match as much of the
1043 string as possible, while still allowing the regexp to succeed. Thus
1044 with C</a?.../>, Perl will first try to match the regexp with the C<a>
1045 present; if that fails, Perl will try to match the regexp without the
1046 C<a> present. For the quantifier C<*>, we get the following:
1048 $x = "the cat in the hat";
1049 $x =~ /^(.*)(cat)(.*)$/; # matches,
1052 # $3 = ' in the hat'
1054 Which is what we might expect, the match finds the only C<cat> in the
1055 string and locks onto it. Consider, however, this regexp:
1057 $x =~ /^(.*)(at)(.*)$/; # matches,
1058 # $1 = 'the cat in the h'
1060 # $3 = '' (0 characters match)
1062 One might initially guess that Perl would find the C<at> in C<cat> and
1063 stop there, but that wouldn't give the longest possible string to the
1064 first quantifier C<.*>. Instead, the first quantifier C<.*> grabs as
1065 much of the string as possible while still having the regexp match. In
1066 this example, that means having the C<at> sequence with the final C<at>
1067 in the string. The other important principle illustrated here is that,
1068 when there are two or more elements in a regexp, the I<leftmost>
1069 quantifier, if there is one, gets to grab as much of the string as
1070 possible, leaving the rest of the regexp to fight over scraps. Thus in
1071 our example, the first quantifier C<.*> grabs most of the string, while
1072 the second quantifier C<.*> gets the empty string. Quantifiers that
1073 grab as much of the string as possible are called I<maximal match> or
1074 I<greedy> quantifiers.
1076 When a regexp can match a string in several different ways, we can use
1077 the principles above to predict which way the regexp will match:
1083 Principle 0: Taken as a whole, any regexp will be matched at the
1084 earliest possible position in the string.
1088 Principle 1: In an alternation C<a|b|c...>, the leftmost alternative
1089 that allows a match for the whole regexp will be the one used.
1093 Principle 2: The maximal matching quantifiers C<?>, C<*>, C<+> and
1094 C<{n,m}> will in general match as much of the string as possible while
1095 still allowing the whole regexp to match.
1099 Principle 3: If there are two or more elements in a regexp, the
1100 leftmost greedy quantifier, if any, will match as much of the string
1101 as possible while still allowing the whole regexp to match. The next
1102 leftmost greedy quantifier, if any, will try to match as much of the
1103 string remaining available to it as possible, while still allowing the
1104 whole regexp to match. And so on, until all the regexp elements are
1109 As we have seen above, Principle 0 overrides the others. The regexp
1110 will be matched as early as possible, with the other principles
1111 determining how the regexp matches at that earliest character
1114 Here is an example of these principles in action:
1116 $x = "The programming republic of Perl";
1117 $x =~ /^(.+)(e|r)(.*)$/; # matches,
1118 # $1 = 'The programming republic of Pe'
1122 This regexp matches at the earliest string position, C<'T'>. One
1123 might think that C<e>, being leftmost in the alternation, would be
1124 matched, but C<r> produces the longest string in the first quantifier.
1126 $x =~ /(m{1,2})(.*)$/; # matches,
1128 # $2 = 'ing republic of Perl'
1130 Here, The earliest possible match is at the first C<'m'> in
1131 C<programming>. C<m{1,2}> is the first quantifier, so it gets to match
1134 $x =~ /.*(m{1,2})(.*)$/; # matches,
1136 # $2 = 'ing republic of Perl'
1138 Here, the regexp matches at the start of the string. The first
1139 quantifier C<.*> grabs as much as possible, leaving just a single
1140 C<'m'> for the second quantifier C<m{1,2}>.
1142 $x =~ /(.?)(m{1,2})(.*)$/; # matches,
1145 # $3 = 'ing republic of Perl'
1147 Here, C<.?> eats its maximal one character at the earliest possible
1148 position in the string, C<'a'> in C<programming>, leaving C<m{1,2}>
1149 the opportunity to match both C<m>'s. Finally,
1151 "aXXXb" =~ /(X*)/; # matches with $1 = ''
1153 because it can match zero copies of C<'X'> at the beginning of the
1154 string. If you definitely want to match at least one C<'X'>, use
1157 Sometimes greed is not good. At times, we would like quantifiers to
1158 match a I<minimal> piece of string, rather than a maximal piece. For
1159 this purpose, Larry Wall created the I<minimal match> or
1160 I<non-greedy> quantifiers C<??>, C<*?>, C<+?>, and C<{}?>. These are
1161 the usual quantifiers with a C<?> appended to them. They have the
1168 C<a??> means: match 'a' 0 or 1 times. Try 0 first, then 1.
1172 C<a*?> means: match 'a' 0 or more times, i.e., any number of times,
1173 but as few times as possible
1177 C<a+?> means: match 'a' 1 or more times, i.e., at least once, but
1178 as few times as possible
1182 C<a{n,m}?> means: match at least C<n> times, not more than C<m>
1183 times, as few times as possible
1187 C<a{n,}?> means: match at least C<n> times, but as few times as
1192 C<a{n}?> means: match exactly C<n> times. Because we match exactly
1193 C<n> times, C<a{n}?> is equivalent to C<a{n}> and is just there for
1194 notational consistency.
1198 Let's look at the example above, but with minimal quantifiers:
1200 $x = "The programming republic of Perl";
1201 $x =~ /^(.+?)(e|r)(.*)$/; # matches,
1204 # $3 = ' programming republic of Perl'
1206 The minimal string that will allow both the start of the string C<^>
1207 and the alternation to match is C<Th>, with the alternation C<e|r>
1208 matching C<e>. The second quantifier C<.*> is free to gobble up the
1211 $x =~ /(m{1,2}?)(.*?)$/; # matches,
1213 # $2 = 'ming republic of Perl'
1215 The first string position that this regexp can match is at the first
1216 C<'m'> in C<programming>. At this position, the minimal C<m{1,2}?>
1217 matches just one C<'m'>. Although the second quantifier C<.*?> would
1218 prefer to match no characters, it is constrained by the end-of-string
1219 anchor C<$> to match the rest of the string.
1221 $x =~ /(.*?)(m{1,2}?)(.*)$/; # matches,
1224 # $3 = 'ming republic of Perl'
1226 In this regexp, you might expect the first minimal quantifier C<.*?>
1227 to match the empty string, because it is not constrained by a C<^>
1228 anchor to match the beginning of the word. Principle 0 applies here,
1229 however. Because it is possible for the whole regexp to match at the
1230 start of the string, it I<will> match at the start of the string. Thus
1231 the first quantifier has to match everything up to the first C<m>. The
1232 second minimal quantifier matches just one C<m> and the third
1233 quantifier matches the rest of the string.
1235 $x =~ /(.??)(m{1,2})(.*)$/; # matches,
1238 # $3 = 'ing republic of Perl'
1240 Just as in the previous regexp, the first quantifier C<.??> can match
1241 earliest at position C<'a'>, so it does. The second quantifier is
1242 greedy, so it matches C<mm>, and the third matches the rest of the
1245 We can modify principle 3 above to take into account non-greedy
1252 Principle 3: If there are two or more elements in a regexp, the
1253 leftmost greedy (non-greedy) quantifier, if any, will match as much
1254 (little) of the string as possible while still allowing the whole
1255 regexp to match. The next leftmost greedy (non-greedy) quantifier, if
1256 any, will try to match as much (little) of the string remaining
1257 available to it as possible, while still allowing the whole regexp to
1258 match. And so on, until all the regexp elements are satisfied.
1262 Just like alternation, quantifiers are also susceptible to
1263 backtracking. Here is a step-by-step analysis of the example
1265 $x = "the cat in the hat";
1266 $x =~ /^(.*)(at)(.*)$/; # matches,
1267 # $1 = 'the cat in the h'
1269 # $3 = '' (0 matches)
1275 Start with the first letter in the string 't'.
1279 The first quantifier '.*' starts out by matching the whole
1280 string 'the cat in the hat'.
1284 'a' in the regexp element 'at' doesn't match the end of the
1285 string. Backtrack one character.
1289 'a' in the regexp element 'at' still doesn't match the last
1290 letter of the string 't', so backtrack one more character.
1294 Now we can match the 'a' and the 't'.
1298 Move on to the third element '.*'. Since we are at the end of
1299 the string and '.*' can match 0 times, assign it the empty string.
1307 Most of the time, all this moving forward and backtracking happens
1308 quickly and searching is fast. There are some pathological regexps,
1309 however, whose execution time exponentially grows with the size of the
1310 string. A typical structure that blows up in your face is of the form
1314 The problem is the nested indeterminate quantifiers. There are many
1315 different ways of partitioning a string of length n between the C<+>
1316 and C<*>: one repetition with C<b+> of length n, two repetitions with
1317 the first C<b+> length k and the second with length n-k, m repetitions
1318 whose bits add up to length n, etc. In fact there are an exponential
1319 number of ways to partition a string as a function of its length. A
1320 regexp may get lucky and match early in the process, but if there is
1321 no match, Perl will try I<every> possibility before giving up. So be
1322 careful with nested C<*>'s, C<{n,m}>'s, and C<+>'s. The book
1323 I<Mastering Regular Expressions> by Jeffrey Friedl gives a wonderful
1324 discussion of this and other efficiency issues.
1327 =head2 Possessive quantifiers
1329 Backtracking during the relentless search for a match may be a waste
1330 of time, particularly when the match is bound to fail. Consider
1333 /^\w+\s+\w+$/; # a word, spaces, a word
1335 Whenever this is applied to a string which doesn't quite meet the
1336 pattern's expectations such as S<C<"abc ">> or S<C<"abc def ">>,
1337 the regex engine will backtrack, approximately once for each character
1338 in the string. But we know that there is no way around taking I<all>
1339 of the initial word characters to match the first repetition, that I<all>
1340 spaces must be eaten by the middle part, and the same goes for the second
1343 With the introduction of the I<possessive quantifiers> in Perl 5.10, we
1344 have a way of instructing the regex engine not to backtrack, with the
1345 usual quantifiers with a C<+> appended to them. This makes them greedy as
1346 well as stingy; once they succeed they won't give anything back to permit
1347 another solution. They have the following meanings:
1353 C<a{n,m}+> means: match at least C<n> times, not more than C<m> times,
1354 as many times as possible, and don't give anything up. C<a?+> is short
1359 C<a{n,}+> means: match at least C<n> times, but as many times as possible,
1360 and don't give anything up. C<a*+> is short for C<a{0,}+> and C<a++> is
1361 short for C<a{1,}+>.
1365 C<a{n}+> means: match exactly C<n> times. It is just there for
1366 notational consistency.
1370 These possessive quantifiers represent a special case of a more general
1371 concept, the I<independent subexpression>, see below.
1373 As an example where a possessive quantifier is suitable we consider
1374 matching a quoted string, as it appears in several programming languages.
1375 The backslash is used as an escape character that indicates that the
1376 next character is to be taken literally, as another character for the
1377 string. Therefore, after the opening quote, we expect a (possibly
1378 empty) sequence of alternatives: either some character except an
1379 unescaped quote or backslash or an escaped character.
1381 /"(?:[^"\\]++|\\.)*+"/;
1384 =head2 Building a regexp
1386 At this point, we have all the basic regexp concepts covered, so let's
1387 give a more involved example of a regular expression. We will build a
1388 regexp that matches numbers.
1390 The first task in building a regexp is to decide what we want to match
1391 and what we want to exclude. In our case, we want to match both
1392 integers and floating point numbers and we want to reject any string
1393 that isn't a number.
1395 The next task is to break the problem down into smaller problems that
1396 are easily converted into a regexp.
1398 The simplest case is integers. These consist of a sequence of digits,
1399 with an optional sign in front. The digits we can represent with
1400 C<\d+> and the sign can be matched with C<[+-]>. Thus the integer
1403 /[+-]?\d+/; # matches integers
1405 A floating point number potentially has a sign, an integral part, a
1406 decimal point, a fractional part, and an exponent. One or more of these
1407 parts is optional, so we need to check out the different
1408 possibilities. Floating point numbers which are in proper form include
1409 123., 0.345, .34, -1e6, and 25.4E-72. As with integers, the sign out
1410 front is completely optional and can be matched by C<[+-]?>. We can
1411 see that if there is no exponent, floating point numbers must have a
1412 decimal point, otherwise they are integers. We might be tempted to
1413 model these with C<\d*\.\d*>, but this would also match just a single
1414 decimal point, which is not a number. So the three cases of floating
1415 point number without exponent are
1417 /[+-]?\d+\./; # 1., 321., etc.
1418 /[+-]?\.\d+/; # .1, .234, etc.
1419 /[+-]?\d+\.\d+/; # 1.0, 30.56, etc.
1421 These can be combined into a single regexp with a three-way alternation:
1423 /[+-]?(\d+\.\d+|\d+\.|\.\d+)/; # floating point, no exponent
1425 In this alternation, it is important to put C<'\d+\.\d+'> before
1426 C<'\d+\.'>. If C<'\d+\.'> were first, the regexp would happily match that
1427 and ignore the fractional part of the number.
1429 Now consider floating point numbers with exponents. The key
1430 observation here is that I<both> integers and numbers with decimal
1431 points are allowed in front of an exponent. Then exponents, like the
1432 overall sign, are independent of whether we are matching numbers with
1433 or without decimal points, and can be 'decoupled' from the
1434 mantissa. The overall form of the regexp now becomes clear:
1436 /^(optional sign)(integer | f.p. mantissa)(optional exponent)$/;
1438 The exponent is an C<e> or C<E>, followed by an integer. So the
1441 /[eE][+-]?\d+/; # exponent
1443 Putting all the parts together, we get a regexp that matches numbers:
1445 /^[+-]?(\d+\.\d+|\d+\.|\.\d+|\d+)([eE][+-]?\d+)?$/; # Ta da!
1447 Long regexps like this may impress your friends, but can be hard to
1448 decipher. In complex situations like this, the C<//x> modifier for a
1449 match is invaluable. It allows one to put nearly arbitrary whitespace
1450 and comments into a regexp without affecting their meaning. Using it,
1451 we can rewrite our 'extended' regexp in the more pleasing form
1454 [+-]? # first, match an optional sign
1455 ( # then match integers or f.p. mantissas:
1456 \d+\.\d+ # mantissa of the form a.b
1457 |\d+\. # mantissa of the form a.
1458 |\.\d+ # mantissa of the form .b
1459 |\d+ # integer of the form a
1461 ([eE][+-]?\d+)? # finally, optionally match an exponent
1464 If whitespace is mostly irrelevant, how does one include space
1465 characters in an extended regexp? The answer is to backslash it
1466 S<C<'\ '>> or put it in a character class S<C<[ ]>>. The same thing
1467 goes for pound signs: use C<\#> or C<[#]>. For instance, Perl allows
1468 a space between the sign and the mantissa or integer, and we could add
1469 this to our regexp as follows:
1472 [+-]?\ * # first, match an optional sign *and space*
1473 ( # then match integers or f.p. mantissas:
1474 \d+\.\d+ # mantissa of the form a.b
1475 |\d+\. # mantissa of the form a.
1476 |\.\d+ # mantissa of the form .b
1477 |\d+ # integer of the form a
1479 ([eE][+-]?\d+)? # finally, optionally match an exponent
1482 In this form, it is easier to see a way to simplify the
1483 alternation. Alternatives 1, 2, and 4 all start with C<\d+>, so it
1484 could be factored out:
1487 [+-]?\ * # first, match an optional sign
1488 ( # then match integers or f.p. mantissas:
1489 \d+ # start out with a ...
1491 \.\d* # mantissa of the form a.b or a.
1492 )? # ? takes care of integers of the form a
1493 |\.\d+ # mantissa of the form .b
1495 ([eE][+-]?\d+)? # finally, optionally match an exponent
1498 or written in the compact form,
1500 /^[+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/;
1502 This is our final regexp. To recap, we built a regexp by
1508 specifying the task in detail,
1512 breaking down the problem into smaller parts,
1516 translating the small parts into regexps,
1520 combining the regexps,
1524 and optimizing the final combined regexp.
1528 These are also the typical steps involved in writing a computer
1529 program. This makes perfect sense, because regular expressions are
1530 essentially programs written in a little computer language that specifies
1533 =head2 Using regular expressions in Perl
1535 The last topic of Part 1 briefly covers how regexps are used in Perl
1536 programs. Where do they fit into Perl syntax?
1538 We have already introduced the matching operator in its default
1539 C</regexp/> and arbitrary delimiter C<m!regexp!> forms. We have used
1540 the binding operator C<=~> and its negation C<!~> to test for string
1541 matches. Associated with the matching operator, we have discussed the
1542 single line C<//s>, multi-line C<//m>, case-insensitive C<//i> and
1543 extended C<//x> modifiers. There are a few more things you might
1544 want to know about matching operators.
1546 =head3 Prohibiting substitution
1548 If you change C<$pattern> after the first substitution happens, Perl
1549 will ignore it. If you don't want any substitutions at all, use the
1550 special delimiter C<m''>:
1552 @pattern = ('Seuss');
1554 print if m'@pattern'; # matches literal '@pattern', not 'Seuss'
1557 Similar to strings, C<m''> acts like apostrophes on a regexp; all other
1558 C<m> delimiters act like quotes. If the regexp evaluates to the empty string,
1559 the regexp in the I<last successful match> is used instead. So we have
1561 "dog" =~ /d/; # 'd' matches
1562 "dogbert =~ //; # this matches the 'd' regexp used before
1565 =head3 Global matching
1567 The final two modifiers we will discuss here,
1568 C<//g> and C<//c>, concern multiple matches.
1569 The modifier C<//g> stands for global matching and allows the
1570 matching operator to match within a string as many times as possible.
1571 In scalar context, successive invocations against a string will have
1572 C<//g> jump from match to match, keeping track of position in the
1573 string as it goes along. You can get or set the position with the
1576 The use of C<//g> is shown in the following example. Suppose we have
1577 a string that consists of words separated by spaces. If we know how
1578 many words there are in advance, we could extract the words using
1581 $x = "cat dog house"; # 3 words
1582 $x =~ /^\s*(\w+)\s+(\w+)\s+(\w+)\s*$/; # matches,
1587 But what if we had an indeterminate number of words? This is the sort
1588 of task C<//g> was made for. To extract all words, form the simple
1589 regexp C<(\w+)> and loop over all matches with C</(\w+)/g>:
1591 while ($x =~ /(\w+)/g) {
1592 print "Word is $1, ends at position ", pos $x, "\n";
1597 Word is cat, ends at position 3
1598 Word is dog, ends at position 7
1599 Word is house, ends at position 13
1601 A failed match or changing the target string resets the position. If
1602 you don't want the position reset after failure to match, add the
1603 C<//c>, as in C</regexp/gc>. The current position in the string is
1604 associated with the string, not the regexp. This means that different
1605 strings have different positions and their respective positions can be
1606 set or read independently.
1608 In list context, C<//g> returns a list of matched groupings, or if
1609 there are no groupings, a list of matches to the whole regexp. So if
1610 we wanted just the words, we could use
1612 @words = ($x =~ /(\w+)/g); # matches,
1615 # $words[2] = 'house'
1617 Closely associated with the C<//g> modifier is the C<\G> anchor. The
1618 C<\G> anchor matches at the point where the previous C<//g> match left
1619 off. C<\G> allows us to easily do context-sensitive matching:
1621 $metric = 1; # use metric units
1623 $x = <FILE>; # read in measurement
1624 $x =~ /^([+-]?\d+)\s*/g; # get magnitude
1626 if ($metric) { # error checking
1627 print "Units error!" unless $x =~ /\Gkg\./g;
1630 print "Units error!" unless $x =~ /\Glbs\./g;
1632 $x =~ /\G\s+(widget|sprocket)/g; # continue processing
1634 The combination of C<//g> and C<\G> allows us to process the string a
1635 bit at a time and use arbitrary Perl logic to decide what to do next.
1636 Currently, the C<\G> anchor is only fully supported when used to anchor
1637 to the start of the pattern.
1639 C<\G> is also invaluable in processing fixed-length records with
1640 regexps. Suppose we have a snippet of coding region DNA, encoded as
1641 base pair letters C<ATCGTTGAAT...> and we want to find all the stop
1642 codons C<TGA>. In a coding region, codons are 3-letter sequences, so
1643 we can think of the DNA snippet as a sequence of 3-letter records. The
1646 # expanded, this is "ATC GTT GAA TGC AAA TGA CAT GAC"
1647 $dna = "ATCGTTGAATGCAAATGACATGAC";
1650 doesn't work; it may match a C<TGA>, but there is no guarantee that
1651 the match is aligned with codon boundaries, e.g., the substring
1652 S<C<GTT GAA>> gives a match. A better solution is
1654 while ($dna =~ /(\w\w\w)*?TGA/g) { # note the minimal *?
1655 print "Got a TGA stop codon at position ", pos $dna, "\n";
1660 Got a TGA stop codon at position 18
1661 Got a TGA stop codon at position 23
1663 Position 18 is good, but position 23 is bogus. What happened?
1665 The answer is that our regexp works well until we get past the last
1666 real match. Then the regexp will fail to match a synchronized C<TGA>
1667 and start stepping ahead one character position at a time, not what we
1668 want. The solution is to use C<\G> to anchor the match to the codon
1671 while ($dna =~ /\G(\w\w\w)*?TGA/g) {
1672 print "Got a TGA stop codon at position ", pos $dna, "\n";
1677 Got a TGA stop codon at position 18
1679 which is the correct answer. This example illustrates that it is
1680 important not only to match what is desired, but to reject what is not
1683 (There are other regexp modifiers that are available, such as
1684 C<//o>, but their specialized uses are beyond the
1685 scope of this introduction. )
1687 =head3 Search and replace
1689 Regular expressions also play a big role in I<search and replace>
1690 operations in Perl. Search and replace is accomplished with the
1691 C<s///> operator. The general form is
1692 C<s/regexp/replacement/modifiers>, with everything we know about
1693 regexps and modifiers applying in this case as well. The
1694 C<replacement> is a Perl double-quoted string that replaces in the
1695 string whatever is matched with the C<regexp>. The operator C<=~> is
1696 also used here to associate a string with C<s///>. If matching
1697 against C<$_>, the S<C<$_ =~>> can be dropped. If there is a match,
1698 C<s///> returns the number of substitutions made; otherwise it returns
1699 false. Here are a few examples:
1701 $x = "Time to feed the cat!";
1702 $x =~ s/cat/hacker/; # $x contains "Time to feed the hacker!"
1703 if ($x =~ s/^(Time.*hacker)!$/$1 now!/) {
1704 $more_insistent = 1;
1706 $y = "'quoted words'";
1707 $y =~ s/^'(.*)'$/$1/; # strip single quotes,
1708 # $y contains "quoted words"
1710 In the last example, the whole string was matched, but only the part
1711 inside the single quotes was grouped. With the C<s///> operator, the
1712 matched variables C<$1>, C<$2>, etc. are immediately available for use
1713 in the replacement expression, so we use C<$1> to replace the quoted
1714 string with just what was quoted. With the global modifier, C<s///g>
1715 will search and replace all occurrences of the regexp in the string:
1717 $x = "I batted 4 for 4";
1718 $x =~ s/4/four/; # doesn't do it all:
1719 # $x contains "I batted four for 4"
1720 $x = "I batted 4 for 4";
1721 $x =~ s/4/four/g; # does it all:
1722 # $x contains "I batted four for four"
1724 If you prefer 'regex' over 'regexp' in this tutorial, you could use
1725 the following program to replace it:
1727 % cat > simple_replace
1730 $replacement = shift;
1732 s/$regexp/$replacement/g;
1737 % simple_replace regexp regex perlretut.pod
1739 In C<simple_replace> we used the C<s///g> modifier to replace all
1740 occurrences of the regexp on each line. (Even though the regular
1741 expression appears in a loop, Perl is smart enough to compile it
1742 only once.) As with C<simple_grep>, both the
1743 C<print> and the C<s/$regexp/$replacement/g> use C<$_> implicitly.
1745 If you don't want C<s///> to change your original variable you can use
1746 the non-destructive substitute modifier, C<s///r>. This changes the
1747 behavior so that C<s///r> returns the final substituted string
1748 (instead of the number of substitutions):
1750 $x = "I like dogs.";
1751 $y = $x =~ s/dogs/cats/r;
1754 That example will print "I like dogs. I like cats". Notice the original
1755 C<$x> variable has not been affected. The overall
1756 result of the substitution is instead stored in C<$y>. If the
1757 substitution doesn't affect anything then the original string is
1760 $x = "I like dogs.";
1761 $y = $x =~ s/elephants/cougars/r;
1762 print "$x $y\n"; # prints "I like dogs. I like dogs."
1764 One other interesting thing that the C<s///r> flag allows is chaining
1767 $x = "Cats are great.";
1768 print $x =~ s/Cats/Dogs/r =~ s/Dogs/Frogs/r =~
1769 s/Frogs/Hedgehogs/r, "\n";
1770 # prints "Hedgehogs are great."
1772 A modifier available specifically to search and replace is the
1773 C<s///e> evaluation modifier. C<s///e> treats the
1774 replacement text as Perl code, rather than a double-quoted
1775 string. The value that the code returns is substituted for the
1776 matched substring. C<s///e> is useful if you need to do a bit of
1777 computation in the process of replacing text. This example counts
1778 character frequencies in a line:
1780 $x = "Bill the cat";
1781 $x =~ s/(.)/$chars{$1}++;$1/eg; # final $1 replaces char with itself
1782 print "frequency of '$_' is $chars{$_}\n"
1783 foreach (sort {$chars{$b} <=> $chars{$a}} keys %chars);
1787 frequency of ' ' is 2
1788 frequency of 't' is 2
1789 frequency of 'l' is 2
1790 frequency of 'B' is 1
1791 frequency of 'c' is 1
1792 frequency of 'e' is 1
1793 frequency of 'h' is 1
1794 frequency of 'i' is 1
1795 frequency of 'a' is 1
1797 As with the match C<m//> operator, C<s///> can use other delimiters,
1798 such as C<s!!!> and C<s{}{}>, and even C<s{}//>. If single quotes are
1799 used C<s'''>, then the regexp and replacement are
1800 treated as single-quoted strings and there are no
1801 variable substitutions. C<s///> in list context
1802 returns the same thing as in scalar context, i.e., the number of
1805 =head3 The split function
1807 The C<split()> function is another place where a regexp is used.
1808 C<split /regexp/, string, limit> separates the C<string> operand into
1809 a list of substrings and returns that list. The regexp must be designed
1810 to match whatever constitutes the separators for the desired substrings.
1811 The C<limit>, if present, constrains splitting into no more than C<limit>
1812 number of strings. For example, to split a string into words, use
1814 $x = "Calvin and Hobbes";
1815 @words = split /\s+/, $x; # $word[0] = 'Calvin'
1817 # $word[2] = 'Hobbes'
1819 If the empty regexp C<//> is used, the regexp always matches and
1820 the string is split into individual characters. If the regexp has
1821 groupings, then the resulting list contains the matched substrings from the
1822 groupings as well. For instance,
1824 $x = "/usr/bin/perl";
1825 @dirs = split m!/!, $x; # $dirs[0] = ''
1829 @parts = split m!(/)!, $x; # $parts[0] = ''
1835 # $parts[6] = 'perl'
1837 Since the first character of $x matched the regexp, C<split> prepended
1838 an empty initial element to the list.
1840 If you have read this far, congratulations! You now have all the basic
1841 tools needed to use regular expressions to solve a wide range of text
1842 processing problems. If this is your first time through the tutorial,
1843 why not stop here and play around with regexps a while.... S<Part 2>
1844 concerns the more esoteric aspects of regular expressions and those
1845 concepts certainly aren't needed right at the start.
1847 =head1 Part 2: Power tools
1849 OK, you know the basics of regexps and you want to know more. If
1850 matching regular expressions is analogous to a walk in the woods, then
1851 the tools discussed in Part 1 are analogous to topo maps and a
1852 compass, basic tools we use all the time. Most of the tools in part 2
1853 are analogous to flare guns and satellite phones. They aren't used
1854 too often on a hike, but when we are stuck, they can be invaluable.
1856 What follows are the more advanced, less used, or sometimes esoteric
1857 capabilities of Perl regexps. In Part 2, we will assume you are
1858 comfortable with the basics and concentrate on the advanced features.
1860 =head2 More on characters, strings, and character classes
1862 There are a number of escape sequences and character classes that we
1863 haven't covered yet.
1865 There are several escape sequences that convert characters or strings
1866 between upper and lower case, and they are also available within
1867 patterns. C<\l> and C<\u> convert the next character to lower or
1868 upper case, respectively:
1871 $string =~ /\u$x/; # matches 'Perl' in $string
1872 $x = "M(rs?|s)\\."; # note the double backslash
1873 $string =~ /\l$x/; # matches 'mr.', 'mrs.', and 'ms.',
1875 A C<\L> or C<\U> indicates a lasting conversion of case, until
1876 terminated by C<\E> or thrown over by another C<\U> or C<\L>:
1878 $x = "This word is in lower case:\L SHOUT\E";
1879 $x =~ /shout/; # matches
1880 $x = "I STILL KEYPUNCH CARDS FOR MY 360"
1881 $x =~ /\Ukeypunch/; # matches punch card string
1883 If there is no C<\E>, case is converted until the end of the
1884 string. The regexps C<\L\u$word> or C<\u\L$word> convert the first
1885 character of C<$word> to uppercase and the rest of the characters to
1888 Control characters can be escaped with C<\c>, so that a control-Z
1889 character would be matched with C<\cZ>. The escape sequence
1890 C<\Q>...C<\E> quotes, or protects most non-alphabetic characters. For
1893 $x = "\QThat !^*&%~& cat!";
1894 $x =~ /\Q!^*&%~&\E/; # check for rough language
1896 It does not protect C<$> or C<@>, so that variables can still be
1899 C<\Q>, C<\L>, C<\l>, C<\U>, C<\u> and C<\E> are actually part of
1900 double-quotish syntax, and not part of regexp syntax proper. They will
1901 work if they appear in a regular expression embedded directly in a
1902 program, but not when contained in a string that is interpolated in a
1905 Perl regexps can handle more than just the
1906 standard ASCII character set. Perl supports I<Unicode>, a standard
1907 for representing the alphabets from virtually all of the world's written
1908 languages, and a host of symbols. Perl's text strings are Unicode strings, so
1909 they can contain characters with a value (codepoint or character number) higher
1912 What does this mean for regexps? Well, regexp users don't need to know
1913 much about Perl's internal representation of strings. But they do need
1914 to know 1) how to represent Unicode characters in a regexp and 2) that
1915 a matching operation will treat the string to be searched as a sequence
1916 of characters, not bytes. The answer to 1) is that Unicode characters
1917 greater than C<chr(255)> are represented using the C<\x{hex}> notation, because
1918 \x hex (without curly braces) doesn't go further than 255. (Starting in Perl
1919 5.14, if you're an octal fan, you can also use C<\o{oct}>.)
1921 /\x{263a}/; # match a Unicode smiley face :)
1923 B<NOTE>: In Perl 5.6.0 it used to be that one needed to say C<use
1924 utf8> to use any Unicode features. This is no more the case: for
1925 almost all Unicode processing, the explicit C<utf8> pragma is not
1926 needed. (The only case where it matters is if your Perl script is in
1927 Unicode and encoded in UTF-8, then an explicit C<use utf8> is needed.)
1929 Figuring out the hexadecimal sequence of a Unicode character you want
1930 or deciphering someone else's hexadecimal Unicode regexp is about as
1931 much fun as programming in machine code. So another way to specify
1932 Unicode characters is to use the I<named character> escape
1933 sequence C<\N{I<name>}>. I<name> is a name for the Unicode character, as
1934 specified in the Unicode standard. For instance, if we wanted to
1935 represent or match the astrological sign for the planet Mercury, we
1938 $x = "abc\N{MERCURY}def";
1939 $x =~ /\N{MERCURY}/; # matches
1941 One can also use "short" names:
1943 print "\N{GREEK SMALL LETTER SIGMA} is called sigma.\n";
1944 print "\N{greek:Sigma} is an upper-case sigma.\n";
1946 You can also restrict names to a certain alphabet by specifying the
1947 L<charnames> pragma:
1949 use charnames qw(greek);
1950 print "\N{sigma} is Greek sigma\n";
1952 An index of character names is available on-line from the Unicode
1953 Consortium, L<http://www.unicode.org/charts/charindex.html>; explanatory
1954 material with links to other resources at
1955 L<http://www.unicode.org/standard/where>.
1957 The answer to requirement 2) is that a regexp (mostly)
1958 uses Unicode characters. The "mostly" is for messy backward
1959 compatibility reasons, but starting in Perl 5.14, any regex compiled in
1960 the scope of a C<use feature 'unicode_strings'> (which is automatically
1961 turned on within the scope of a C<use 5.012> or higher) will turn that
1962 "mostly" into "always". If you want to handle Unicode properly, you
1963 should ensure that C<'unicode_strings'> is turned on.
1964 Internally, this is encoded to bytes using either UTF-8 or a native 8
1965 bit encoding, depending on the history of the string, but conceptually
1966 it is a sequence of characters, not bytes. See L<perlunitut> for a
1967 tutorial about that.
1969 Let us now discuss Unicode character classes, most usually called
1970 "character properties". These are represented by the
1971 C<\p{name}> escape sequence. Closely associated is the C<\P{name}>
1972 property, which is the negation of the C<\p{name}> one. For
1973 example, to match lower and uppercase characters,
1976 $x =~ /^\p{IsUpper}/; # matches, uppercase char class
1977 $x =~ /^\P{IsUpper}/; # doesn't match, char class sans uppercase
1978 $x =~ /^\p{IsLower}/; # doesn't match, lowercase char class
1979 $x =~ /^\P{IsLower}/; # matches, char class sans lowercase
1981 (The "Is" is optional.)
1983 There are many, many Unicode character properties. For the full list
1984 see L<perluniprops>. Most of them have synonyms with shorter names,
1985 also listed there. Some synonyms are a single character. For these,
1986 you can drop the braces. For instance, C<\pM> is the same thing as
1987 C<\p{Mark}>, meaning things like accent marks.
1989 The Unicode C<\p{Script}> and C<\p{Script_Extensions}> properties are
1990 used to categorize every Unicode character into the language script it
1991 is written in. (C<Script_Extensions> is an improved version of
1992 C<Script>, which is retained for backward compatibility, and so you
1993 should generally use C<Script_Extensions>.)
1995 English, French, and a bunch of other European languages are written in
1996 the Latin script. But there is also the Greek script, the Thai script,
1997 the Katakana script, etc. You can test whether a character is in a
1998 particular script (based on C<Script_Extensions>) with, for example
1999 C<\p{Latin}>, C<\p{Greek}>, or C<\p{Katakana}>. To test if it isn't in
2000 the Balinese script, you would use C<\P{Balinese}>.
2002 What we have described so far is the single form of the C<\p{...}> character
2003 classes. There is also a compound form which you may run into. These
2004 look like C<\p{name=value}> or C<\p{name:value}> (the equals sign and colon
2005 can be used interchangeably). These are more general than the single form,
2006 and in fact most of the single forms are just Perl-defined shortcuts for common
2007 compound forms. For example, the script examples in the previous paragraph
2008 could be written equivalently as C<\p{Script_Extensions=Latin}>, C<\p{Script_Extensions:Greek}>,
2009 C<\p{script_extensions=katakana}>, and C<\P{script_extensions=balinese}> (case is irrelevant
2010 between the C<{}> braces). You may
2011 never have to use the compound forms, but sometimes it is necessary, and their
2012 use can make your code easier to understand.
2014 C<\X> is an abbreviation for a character class that comprises
2015 a Unicode I<extended grapheme cluster>. This represents a "logical character":
2016 what appears to be a single character, but may be represented internally by more
2017 than one. As an example, using the Unicode full names, e.g., S<C<A + COMBINING
2018 RING>> is a grapheme cluster with base character C<A> and combining character
2019 S<C<COMBINING RING>>, which translates in Danish to A with the circle atop it,
2020 as in the word E<Aring>ngstrom.
2022 For the full and latest information about Unicode see the latest
2023 Unicode standard, or the Unicode Consortium's website L<http://www.unicode.org>
2025 As if all those classes weren't enough, Perl also defines POSIX-style
2026 character classes. These have the form C<[:name:]>, with C<name> the
2027 name of the POSIX class. The POSIX classes are C<alpha>, C<alnum>,
2028 C<ascii>, C<cntrl>, C<digit>, C<graph>, C<lower>, C<print>, C<punct>,
2029 C<space>, C<upper>, and C<xdigit>, and two extensions, C<word> (a Perl
2030 extension to match C<\w>), and C<blank> (a GNU extension). The C<//a>
2031 modifier restricts these to matching just in the ASCII range; otherwise
2032 they can match the same as their corresponding Perl Unicode classes:
2033 C<[:upper:]> is the same as C<\p{IsUpper}>, etc. (There are some
2034 exceptions and gotchas with this; see L<perlrecharclass> for a full
2035 discussion.) The C<[:digit:]>, C<[:word:]>, and
2036 C<[:space:]> correspond to the familiar C<\d>, C<\w>, and C<\s>
2037 character classes. To negate a POSIX class, put a C<^> in front of
2038 the name, so that, e.g., C<[:^digit:]> corresponds to C<\D> and, under
2039 Unicode, C<\P{IsDigit}>. The Unicode and POSIX character classes can
2040 be used just like C<\d>, with the exception that POSIX character
2041 classes can only be used inside of a character class:
2043 /\s+[abc[:digit:]xyz]\s*/; # match a,b,c,x,y,z, or a digit
2044 /^=item\s[[:digit:]]/; # match '=item',
2045 # followed by a space and a digit
2046 /\s+[abc\p{IsDigit}xyz]\s+/; # match a,b,c,x,y,z, or a digit
2047 /^=item\s\p{IsDigit}/; # match '=item',
2048 # followed by a space and a digit
2050 Whew! That is all the rest of the characters and character classes.
2052 =head2 Compiling and saving regular expressions
2054 In Part 1 we mentioned that Perl compiles a regexp into a compact
2055 sequence of opcodes. Thus, a compiled regexp is a data structure
2056 that can be stored once and used again and again. The regexp quote
2057 C<qr//> does exactly that: C<qr/string/> compiles the C<string> as a
2058 regexp and transforms the result into a form that can be assigned to a
2061 $reg = qr/foo+bar?/; # reg contains a compiled regexp
2063 Then C<$reg> can be used as a regexp:
2066 $x =~ $reg; # matches, just like /foo+bar?/
2067 $x =~ /$reg/; # same thing, alternate form
2069 C<$reg> can also be interpolated into a larger regexp:
2071 $x =~ /(abc)?$reg/; # still matches
2073 As with the matching operator, the regexp quote can use different
2074 delimiters, e.g., C<qr!!>, C<qr{}> or C<qr~~>. Apostrophes
2075 as delimiters (C<qr''>) inhibit any interpolation.
2077 Pre-compiled regexps are useful for creating dynamic matches that
2078 don't need to be recompiled each time they are encountered. Using
2079 pre-compiled regexps, we write a C<grep_step> program which greps
2080 for a sequence of patterns, advancing to the next pattern as soon
2081 as one has been satisfied.
2085 # grep_step - match <number> regexps, one after the other
2086 # usage: multi_grep <number> regexp1 regexp2 ... file1 file2 ...
2089 $regexp[$_] = shift foreach (0..$number-1);
2090 @compiled = map qr/$_/, @regexp;
2091 while ($line = <>) {
2092 if ($line =~ /$compiled[0]/) {
2095 last unless @compiled;
2100 % grep_step 3 shift print last grep_step
2103 last unless @compiled;
2105 Storing pre-compiled regexps in an array C<@compiled> allows us to
2106 simply loop through the regexps without any recompilation, thus gaining
2107 flexibility without sacrificing speed.
2110 =head2 Composing regular expressions at runtime
2112 Backtracking is more efficient than repeated tries with different regular
2113 expressions. If there are several regular expressions and a match with
2114 any of them is acceptable, then it is possible to combine them into a set
2115 of alternatives. If the individual expressions are input data, this
2116 can be done by programming a join operation. We'll exploit this idea in
2117 an improved version of the C<simple_grep> program: a program that matches
2122 # multi_grep - match any of <number> regexps
2123 # usage: multi_grep <number> regexp1 regexp2 ... file1 file2 ...
2126 $regexp[$_] = shift foreach (0..$number-1);
2127 $pattern = join '|', @regexp;
2129 while ($line = <>) {
2130 print $line if $line =~ /$pattern/;
2134 % multi_grep 2 shift for multi_grep
2136 $regexp[$_] = shift foreach (0..$number-1);
2138 Sometimes it is advantageous to construct a pattern from the I<input>
2139 that is to be analyzed and use the permissible values on the left
2140 hand side of the matching operations. As an example for this somewhat
2141 paradoxical situation, let's assume that our input contains a command
2142 verb which should match one out of a set of available command verbs,
2143 with the additional twist that commands may be abbreviated as long as
2144 the given string is unique. The program below demonstrates the basic
2149 $kwds = 'copy compare list print';
2151 $cmd =~ s/^\s+|\s+$//g; # trim leading and trailing spaces
2152 if( ( @matches = $kwds =~ /\b$cmd\w*/g ) == 1 ){
2153 print "command: '@matches'\n";
2154 } elsif( @matches == 0 ){
2155 print "no such command: '$cmd'\n";
2157 print "not unique: '$cmd' (could be one of: @matches)\n";
2166 not unique: 'co' (could be one of: copy compare)
2168 no such command: 'printer'
2170 Rather than trying to match the input against the keywords, we match the
2171 combined set of keywords against the input. The pattern matching
2172 operation S<C<$kwds =~ /\b($cmd\w*)/g>> does several things at the
2173 same time. It makes sure that the given command begins where a keyword
2174 begins (C<\b>). It tolerates abbreviations due to the added C<\w*>. It
2175 tells us the number of matches (C<scalar @matches>) and all the keywords
2176 that were actually matched. You could hardly ask for more.
2178 =head2 Embedding comments and modifiers in a regular expression
2180 Starting with this section, we will be discussing Perl's set of
2181 I<extended patterns>. These are extensions to the traditional regular
2182 expression syntax that provide powerful new tools for pattern
2183 matching. We have already seen extensions in the form of the minimal
2184 matching constructs C<??>, C<*?>, C<+?>, C<{n,m}?>, and C<{n,}?>. Most
2185 of the extensions below have the form C<(?char...)>, where the
2186 C<char> is a character that determines the type of extension.
2188 The first extension is an embedded comment C<(?#text)>. This embeds a
2189 comment into the regular expression without affecting its meaning. The
2190 comment should not have any closing parentheses in the text. An
2193 /(?# Match an integer:)[+-]?\d+/;
2195 This style of commenting has been largely superseded by the raw,
2196 freeform commenting that is allowed with the C<//x> modifier.
2198 Most modifiers, such as C<//i>, C<//m>, C<//s> and C<//x> (or any
2199 combination thereof) can also be embedded in
2200 a regexp using C<(?i)>, C<(?m)>, C<(?s)>, and C<(?x)>. For instance,
2202 /(?i)yes/; # match 'yes' case insensitively
2203 /yes/i; # same thing
2204 /(?x)( # freeform version of an integer regexp
2205 [+-]? # match an optional sign
2206 \d+ # match a sequence of digits
2210 Embedded modifiers can have two important advantages over the usual
2211 modifiers. Embedded modifiers allow a custom set of modifiers to
2212 I<each> regexp pattern. This is great for matching an array of regexps
2213 that must have different modifiers:
2215 $pattern[0] = '(?i)doctor';
2216 $pattern[1] = 'Johnson';
2219 foreach $patt (@pattern) {
2224 The second advantage is that embedded modifiers (except C<//p>, which
2225 modifies the entire regexp) only affect the regexp
2226 inside the group the embedded modifier is contained in. So grouping
2227 can be used to localize the modifier's effects:
2229 /Answer: ((?i)yes)/; # matches 'Answer: yes', 'Answer: YES', etc.
2231 Embedded modifiers can also turn off any modifiers already present
2232 by using, e.g., C<(?-i)>. Modifiers can also be combined into
2233 a single expression, e.g., C<(?s-i)> turns on single line mode and
2234 turns off case insensitivity.
2236 Embedded modifiers may also be added to a non-capturing grouping.
2237 C<(?i-m:regexp)> is a non-capturing grouping that matches C<regexp>
2238 case insensitively and turns off multi-line mode.
2241 =head2 Looking ahead and looking behind
2243 This section concerns the lookahead and lookbehind assertions. First,
2244 a little background.
2246 In Perl regular expressions, most regexp elements 'eat up' a certain
2247 amount of string when they match. For instance, the regexp element
2248 C<[abc]> eats up one character of the string when it matches, in the
2249 sense that Perl moves to the next character position in the string
2250 after the match. There are some elements, however, that don't eat up
2251 characters (advance the character position) if they match. The examples
2252 we have seen so far are the anchors. The anchor C<^> matches the
2253 beginning of the line, but doesn't eat any characters. Similarly, the
2254 word boundary anchor C<\b> matches wherever a character matching C<\w>
2255 is next to a character that doesn't, but it doesn't eat up any
2256 characters itself. Anchors are examples of I<zero-width assertions>:
2257 zero-width, because they consume
2258 no characters, and assertions, because they test some property of the
2259 string. In the context of our walk in the woods analogy to regexp
2260 matching, most regexp elements move us along a trail, but anchors have
2261 us stop a moment and check our surroundings. If the local environment
2262 checks out, we can proceed forward. But if the local environment
2263 doesn't satisfy us, we must backtrack.
2265 Checking the environment entails either looking ahead on the trail,
2266 looking behind, or both. C<^> looks behind, to see that there are no
2267 characters before. C<$> looks ahead, to see that there are no
2268 characters after. C<\b> looks both ahead and behind, to see if the
2269 characters on either side differ in their "word-ness".
2271 The lookahead and lookbehind assertions are generalizations of the
2272 anchor concept. Lookahead and lookbehind are zero-width assertions
2273 that let us specify which characters we want to test for. The
2274 lookahead assertion is denoted by C<(?=regexp)> and the lookbehind
2275 assertion is denoted by C<< (?<=fixed-regexp) >>. Some examples are
2277 $x = "I catch the housecat 'Tom-cat' with catnip";
2278 $x =~ /cat(?=\s)/; # matches 'cat' in 'housecat'
2279 @catwords = ($x =~ /(?<=\s)cat\w+/g); # matches,
2280 # $catwords[0] = 'catch'
2281 # $catwords[1] = 'catnip'
2282 $x =~ /\bcat\b/; # matches 'cat' in 'Tom-cat'
2283 $x =~ /(?<=\s)cat(?=\s)/; # doesn't match; no isolated 'cat' in
2286 Note that the parentheses in C<(?=regexp)> and C<< (?<=regexp) >> are
2287 non-capturing, since these are zero-width assertions. Thus in the
2288 second regexp, the substrings captured are those of the whole regexp
2289 itself. Lookahead C<(?=regexp)> can match arbitrary regexps, but
2290 lookbehind C<< (?<=fixed-regexp) >> only works for regexps of fixed
2291 width, i.e., a fixed number of characters long. Thus
2292 C<< (?<=(ab|bc)) >> is fine, but C<< (?<=(ab)*) >> is not. The
2293 negated versions of the lookahead and lookbehind assertions are
2294 denoted by C<(?!regexp)> and C<< (?<!fixed-regexp) >> respectively.
2295 They evaluate true if the regexps do I<not> match:
2298 $x =~ /foo(?!bar)/; # doesn't match, 'bar' follows 'foo'
2299 $x =~ /foo(?!baz)/; # matches, 'baz' doesn't follow 'foo'
2300 $x =~ /(?<!\s)foo/; # matches, there is no \s before 'foo'
2302 Here is an example where a string containing blank-separated words,
2303 numbers and single dashes is to be split into its components.
2304 Using C</\s+/> alone won't work, because spaces are not required between
2305 dashes, or a word or a dash. Additional places for a split are established
2306 by looking ahead and behind:
2308 $str = "one two - --6-8";
2309 @toks = split / \s+ # a run of spaces
2310 | (?<=\S) (?=-) # any non-space followed by '-'
2311 | (?<=-) (?=\S) # a '-' followed by any non-space
2312 /x, $str; # @toks = qw(one two - - - 6 - 8)
2315 =head2 Using independent subexpressions to prevent backtracking
2317 I<Independent subexpressions> are regular expressions, in the
2318 context of a larger regular expression, that function independently of
2319 the larger regular expression. That is, they consume as much or as
2320 little of the string as they wish without regard for the ability of
2321 the larger regexp to match. Independent subexpressions are represented
2322 by C<< (?>regexp) >>. We can illustrate their behavior by first
2323 considering an ordinary regexp:
2326 $x =~ /a*ab/; # matches
2328 This obviously matches, but in the process of matching, the
2329 subexpression C<a*> first grabbed the C<a>. Doing so, however,
2330 wouldn't allow the whole regexp to match, so after backtracking, C<a*>
2331 eventually gave back the C<a> and matched the empty string. Here, what
2332 C<a*> matched was I<dependent> on what the rest of the regexp matched.
2334 Contrast that with an independent subexpression:
2336 $x =~ /(?>a*)ab/; # doesn't match!
2338 The independent subexpression C<< (?>a*) >> doesn't care about the rest
2339 of the regexp, so it sees an C<a> and grabs it. Then the rest of the
2340 regexp C<ab> cannot match. Because C<< (?>a*) >> is independent, there
2341 is no backtracking and the independent subexpression does not give
2342 up its C<a>. Thus the match of the regexp as a whole fails. A similar
2343 behavior occurs with completely independent regexps:
2346 $x =~ /a*/g; # matches, eats an 'a'
2347 $x =~ /\Gab/g; # doesn't match, no 'a' available
2349 Here C<//g> and C<\G> create a 'tag team' handoff of the string from
2350 one regexp to the other. Regexps with an independent subexpression are
2351 much like this, with a handoff of the string to the independent
2352 subexpression, and a handoff of the string back to the enclosing
2355 The ability of an independent subexpression to prevent backtracking
2356 can be quite useful. Suppose we want to match a non-empty string
2357 enclosed in parentheses up to two levels deep. Then the following
2360 $x = "abc(de(fg)h"; # unbalanced parentheses
2361 $x =~ /\( ( [^()]+ | \([^()]*\) )+ \)/x;
2363 The regexp matches an open parenthesis, one or more copies of an
2364 alternation, and a close parenthesis. The alternation is two-way, with
2365 the first alternative C<[^()]+> matching a substring with no
2366 parentheses and the second alternative C<\([^()]*\)> matching a
2367 substring delimited by parentheses. The problem with this regexp is
2368 that it is pathological: it has nested indeterminate quantifiers
2369 of the form C<(a+|b)+>. We discussed in Part 1 how nested quantifiers
2370 like this could take an exponentially long time to execute if there
2371 was no match possible. To prevent the exponential blowup, we need to
2372 prevent useless backtracking at some point. This can be done by
2373 enclosing the inner quantifier as an independent subexpression:
2375 $x =~ /\( ( (?>[^()]+) | \([^()]*\) )+ \)/x;
2377 Here, C<< (?>[^()]+) >> breaks the degeneracy of string partitioning
2378 by gobbling up as much of the string as possible and keeping it. Then
2379 match failures fail much more quickly.
2382 =head2 Conditional expressions
2384 A I<conditional expression> is a form of if-then-else statement
2385 that allows one to choose which patterns are to be matched, based on
2386 some condition. There are two types of conditional expression:
2387 C<(?(condition)yes-regexp)> and
2388 C<(?(condition)yes-regexp|no-regexp)>. C<(?(condition)yes-regexp)> is
2389 like an S<C<'if () {}'>> statement in Perl. If the C<condition> is true,
2390 the C<yes-regexp> will be matched. If the C<condition> is false, the
2391 C<yes-regexp> will be skipped and Perl will move onto the next regexp
2392 element. The second form is like an S<C<'if () {} else {}'>> statement
2393 in Perl. If the C<condition> is true, the C<yes-regexp> will be
2394 matched, otherwise the C<no-regexp> will be matched.
2396 The C<condition> can have several forms. The first form is simply an
2397 integer in parentheses C<(integer)>. It is true if the corresponding
2398 backreference C<\integer> matched earlier in the regexp. The same
2399 thing can be done with a name associated with a capture group, written
2400 as C<< (<name>) >> or C<< ('name') >>. The second form is a bare
2401 zero-width assertion C<(?...)>, either a lookahead, a lookbehind, or a
2402 code assertion (discussed in the next section). The third set of forms
2403 provides tests that return true if the expression is executed within
2404 a recursion (C<(R)>) or is being called from some capturing group,
2405 referenced either by number (C<(R1)>, C<(R2)>,...) or by name
2408 The integer or name form of the C<condition> allows us to choose,
2409 with more flexibility, what to match based on what matched earlier in the
2410 regexp. This searches for words of the form C<"$x$x"> or C<"$x$y$y$x">:
2412 % simple_grep '^(\w+)(\w+)?(?(2)\g2\g1|\g1)$' /usr/dict/words
2422 The lookbehind C<condition> allows, along with backreferences,
2423 an earlier part of the match to influence a later part of the
2424 match. For instance,
2426 /[ATGC]+(?(?<=AA)G|C)$/;
2428 matches a DNA sequence such that it either ends in C<AAG>, or some
2429 other base pair combination and C<C>. Note that the form is
2430 C<< (?(?<=AA)G|C) >> and not C<< (?((?<=AA))G|C) >>; for the
2431 lookahead, lookbehind or code assertions, the parentheses around the
2432 conditional are not needed.
2435 =head2 Defining named patterns
2437 Some regular expressions use identical subpatterns in several places.
2438 Starting with Perl 5.10, it is possible to define named subpatterns in
2439 a section of the pattern so that they can be called up by name
2440 anywhere in the pattern. This syntactic pattern for this definition
2441 group is C<< (?(DEFINE)(?<name>pattern)...) >>. An insertion
2442 of a named pattern is written as C<(?&name)>.
2444 The example below illustrates this feature using the pattern for
2445 floating point numbers that was presented earlier on. The three
2446 subpatterns that are used more than once are the optional sign, the
2447 digit sequence for an integer and the decimal fraction. The DEFINE
2448 group at the end of the pattern contains their definition. Notice
2449 that the decimal fraction pattern is the first place where we can
2450 reuse the integer pattern.
2452 /^ (?&osg)\ * ( (?&int)(?&dec)? | (?&dec) )
2453 (?: [eE](?&osg)(?&int) )?
2456 (?<osg>[-+]?) # optional sign
2457 (?<int>\d++) # integer
2458 (?<dec>\.(?&int)) # decimal fraction
2462 =head2 Recursive patterns
2464 This feature (introduced in Perl 5.10) significantly extends the
2465 power of Perl's pattern matching. By referring to some other
2466 capture group anywhere in the pattern with the construct
2467 C<(?group-ref)>, the I<pattern> within the referenced group is used
2468 as an independent subpattern in place of the group reference itself.
2469 Because the group reference may be contained I<within> the group it
2470 refers to, it is now possible to apply pattern matching to tasks that
2471 hitherto required a recursive parser.
2473 To illustrate this feature, we'll design a pattern that matches if
2474 a string contains a palindrome. (This is a word or a sentence that,
2475 while ignoring spaces, interpunctuation and case, reads the same backwards
2476 as forwards. We begin by observing that the empty string or a string
2477 containing just one word character is a palindrome. Otherwise it must
2478 have a word character up front and the same at its end, with another
2479 palindrome in between.
2481 /(?: (\w) (?...Here be a palindrome...) \g{-1} | \w? )/x
2483 Adding C<\W*> at either end to eliminate what is to be ignored, we already
2484 have the full pattern:
2486 my $pp = qr/^(\W* (?: (\w) (?1) \g{-1} | \w? ) \W*)$/ix;
2487 for $s ( "saippuakauppias", "A man, a plan, a canal: Panama!" ){
2488 print "'$s' is a palindrome\n" if $s =~ /$pp/;
2491 In C<(?...)> both absolute and relative backreferences may be used.
2492 The entire pattern can be reinserted with C<(?R)> or C<(?0)>.
2493 If you prefer to name your groups, you can use C<(?&name)> to
2494 recurse into that group.
2497 =head2 A bit of magic: executing Perl code in a regular expression
2499 Normally, regexps are a part of Perl expressions.
2500 I<Code evaluation> expressions turn that around by allowing
2501 arbitrary Perl code to be a part of a regexp. A code evaluation
2502 expression is denoted C<(?{code})>, with I<code> a string of Perl
2505 Be warned that this feature is considered experimental, and may be
2506 changed without notice.
2508 Code expressions are zero-width assertions, and the value they return
2509 depends on their environment. There are two possibilities: either the
2510 code expression is used as a conditional in a conditional expression
2511 C<(?(condition)...)>, or it is not. If the code expression is a
2512 conditional, the code is evaluated and the result (i.e., the result of
2513 the last statement) is used to determine truth or falsehood. If the
2514 code expression is not used as a conditional, the assertion always
2515 evaluates true and the result is put into the special variable
2516 C<$^R>. The variable C<$^R> can then be used in code expressions later
2517 in the regexp. Here are some silly examples:
2520 $x =~ /abc(?{print "Hi Mom!";})def/; # matches,
2522 $x =~ /aaa(?{print "Hi Mom!";})def/; # doesn't match,
2525 Pay careful attention to the next example:
2527 $x =~ /abc(?{print "Hi Mom!";})ddd/; # doesn't match,
2531 At first glance, you'd think that it shouldn't print, because obviously
2532 the C<ddd> isn't going to match the target string. But look at this
2535 $x =~ /abc(?{print "Hi Mom!";})[dD]dd/; # doesn't match,
2538 Hmm. What happened here? If you've been following along, you know that
2539 the above pattern should be effectively (almost) the same as the last one;
2540 enclosing the C<d> in a character class isn't going to change what it
2541 matches. So why does the first not print while the second one does?
2543 The answer lies in the optimizations the regex engine makes. In the first
2544 case, all the engine sees are plain old characters (aside from the
2545 C<?{}> construct). It's smart enough to realize that the string 'ddd'
2546 doesn't occur in our target string before actually running the pattern
2547 through. But in the second case, we've tricked it into thinking that our
2548 pattern is more complicated. It takes a look, sees our
2549 character class, and decides that it will have to actually run the
2550 pattern to determine whether or not it matches, and in the process of
2551 running it hits the print statement before it discovers that we don't
2554 To take a closer look at how the engine does optimizations, see the
2555 section L</"Pragmas and debugging"> below.
2557 More fun with C<?{}>:
2559 $x =~ /(?{print "Hi Mom!";})/; # matches,
2561 $x =~ /(?{$c = 1;})(?{print "$c";})/; # matches,
2563 $x =~ /(?{$c = 1;})(?{print "$^R";})/; # matches,
2566 The bit of magic mentioned in the section title occurs when the regexp
2567 backtracks in the process of searching for a match. If the regexp
2568 backtracks over a code expression and if the variables used within are
2569 localized using C<local>, the changes in the variables produced by the
2570 code expression are undone! Thus, if we wanted to count how many times
2571 a character got matched inside a group, we could use, e.g.,
2574 $count = 0; # initialize 'a' count
2575 $c = "bob"; # test if $c gets clobbered
2576 $x =~ /(?{local $c = 0;}) # initialize count
2578 (?{local $c = $c + 1;}) # increment count
2579 )* # do this any number of times,
2580 aa # but match 'aa' at the end
2581 (?{$count = $c;}) # copy local $c var into $count
2583 print "'a' count is $count, \$c variable is '$c'\n";
2587 'a' count is 2, $c variable is 'bob'
2589 If we replace the S<C< (?{local $c = $c + 1;})>> with
2590 S<C< (?{$c = $c + 1;})>>, the variable changes are I<not> undone
2591 during backtracking, and we get
2593 'a' count is 4, $c variable is 'bob'
2595 Note that only localized variable changes are undone. Other side
2596 effects of code expression execution are permanent. Thus
2599 $x =~ /(a(?{print "Yow\n";}))*aa/;
2608 The result C<$^R> is automatically localized, so that it will behave
2609 properly in the presence of backtracking.
2611 This example uses a code expression in a conditional to match a
2612 definite article, either 'the' in English or 'der|die|das' in German:
2614 $lang = 'DE'; # use German
2619 $lang eq 'EN'; # is the language English?
2621 the | # if so, then match 'the'
2622 (der|die|das) # else, match 'der|die|das'
2626 Note that the syntax here is C<(?(?{...})yes-regexp|no-regexp)>, not
2627 C<(?((?{...}))yes-regexp|no-regexp)>. In other words, in the case of a
2628 code expression, we don't need the extra parentheses around the
2631 If you try to use code expressions where the code text is contained within
2632 an interpolated variable, rather than appearing literally in the pattern,
2633 Perl may surprise you:
2637 /foo(?{ $bar })bar/; # compiles ok, $bar not interpolated
2638 /foo(?{ 1 })$bar/; # compiles ok, $bar interpolated
2639 /foo${pat}bar/; # compile error!
2641 $pat = qr/(?{ $foo = 1 })/; # precompile code regexp
2642 /foo${pat}bar/; # compiles ok
2644 If a regexp has a variable that interpolates a code expression, Perl
2645 treats the regexp as an error. If the code expression is precompiled into
2646 a variable, however, interpolating is ok. The question is, why is this an
2649 The reason is that variable interpolation and code expressions
2650 together pose a security risk. The combination is dangerous because
2651 many programmers who write search engines often take user input and
2652 plug it directly into a regexp:
2654 $regexp = <>; # read user-supplied regexp
2655 $chomp $regexp; # get rid of possible newline
2656 $text =~ /$regexp/; # search $text for the $regexp
2658 If the C<$regexp> variable contains a code expression, the user could
2659 then execute arbitrary Perl code. For instance, some joker could
2660 search for S<C<system('rm -rf *');>> to erase your files. In this
2661 sense, the combination of interpolation and code expressions I<taints>
2662 your regexp. So by default, using both interpolation and code
2663 expressions in the same regexp is not allowed. If you're not
2664 concerned about malicious users, it is possible to bypass this
2665 security check by invoking S<C<use re 'eval'>>:
2667 use re 'eval'; # throw caution out the door
2670 /foo${pat}bar/; # compiles ok
2672 Another form of code expression is the I<pattern code expression>.
2673 The pattern code expression is like a regular code expression, except
2674 that the result of the code evaluation is treated as a regular
2675 expression and matched immediately. A simple example is
2680 $x =~ /(??{$char x $length})/x; # matches, there are 5 of 'a'
2683 This final example contains both ordinary and pattern code
2684 expressions. It detects whether a binary string C<1101010010001...> has a
2685 Fibonacci spacing 0,1,1,2,3,5,... of the C<1>'s:
2687 $x = "1101010010001000001";
2688 $z0 = ''; $z1 = '0'; # initial conditions
2689 print "It is a Fibonacci sequence\n"
2690 if $x =~ /^1 # match an initial '1'
2692 ((??{ $z0 })) # match some '0'
2694 (?{ $z0 = $z1; $z1 .= $^N; })
2695 )+ # repeat as needed
2696 $ # that is all there is
2698 printf "Largest sequence matched was %d\n", length($z1)-length($z0);
2700 Remember that C<$^N> is set to whatever was matched by the last
2701 completed capture group. This prints
2703 It is a Fibonacci sequence
2704 Largest sequence matched was 5
2706 Ha! Try that with your garden variety regexp package...
2708 Note that the variables C<$z0> and C<$z1> are not substituted when the
2709 regexp is compiled, as happens for ordinary variables outside a code
2710 expression. Rather, the whole code block is parsed as perl code at the
2711 same time as perl is compiling the code containing the literal regexp
2714 The regexp without the C<//x> modifier is
2716 /^1(?:((??{ $z0 }))1(?{ $z0 = $z1; $z1 .= $^N; }))+$/
2718 which shows that spaces are still possible in the code parts. Nevertheless,
2719 when working with code and conditional expressions, the extended form of
2720 regexps is almost necessary in creating and debugging regexps.
2723 =head2 Backtracking control verbs
2725 Perl 5.10 introduced a number of control verbs intended to provide
2726 detailed control over the backtracking process, by directly influencing
2727 the regexp engine and by providing monitoring techniques. As all
2728 the features in this group are experimental and subject to change or
2729 removal in a future version of Perl, the interested reader is
2730 referred to L<perlre/"Special Backtracking Control Verbs"> for a
2731 detailed description.
2733 Below is just one example, illustrating the control verb C<(*FAIL)>,
2734 which may be abbreviated as C<(*F)>. If this is inserted in a regexp
2735 it will cause it to fail, just as it would at some
2736 mismatch between the pattern and the string. Processing
2737 of the regexp continues as it would after any "normal"
2738 failure, so that, for instance, the next position in the string or another
2739 alternative will be tried. As failing to match doesn't preserve capture
2740 groups or produce results, it may be necessary to use this in
2741 combination with embedded code.
2744 "supercalifragilisticexpialidocious" =~
2745 /([aeiou])(?{ $count{$1}++; })(*FAIL)/i;
2746 printf "%3d '%s'\n", $count{$_}, $_ for (sort keys %count);
2748 The pattern begins with a class matching a subset of letters. Whenever
2749 this matches, a statement like C<$count{'a'}++;> is executed, incrementing
2750 the letter's counter. Then C<(*FAIL)> does what it says, and
2751 the regexp engine proceeds according to the book: as long as the end of
2752 the string hasn't been reached, the position is advanced before looking
2753 for another vowel. Thus, match or no match makes no difference, and the
2754 regexp engine proceeds until the entire string has been inspected.
2755 (It's remarkable that an alternative solution using something like
2757 $count{lc($_)}++ for split('', "supercalifragilisticexpialidocious");
2758 printf "%3d '%s'\n", $count2{$_}, $_ for ( qw{ a e i o u } );
2760 is considerably slower.)
2763 =head2 Pragmas and debugging
2765 Speaking of debugging, there are several pragmas available to control
2766 and debug regexps in Perl. We have already encountered one pragma in
2767 the previous section, S<C<use re 'eval';>>, that allows variable
2768 interpolation and code expressions to coexist in a regexp. The other
2773 @parts = ($tainted =~ /(\w+)\s+(\w+)/; # @parts is now tainted
2775 The C<taint> pragma causes any substrings from a match with a tainted
2776 variable to be tainted as well. This is not normally the case, as
2777 regexps are often used to extract the safe bits from a tainted
2778 variable. Use C<taint> when you are not extracting safe bits, but are
2779 performing some other processing. Both C<taint> and C<eval> pragmas
2780 are lexically scoped, which means they are in effect only until
2781 the end of the block enclosing the pragmas.
2783 use re '/m'; # or any other flags
2784 $multiline_string =~ /^foo/; # /m is implied
2786 The C<re '/flags'> pragma (introduced in Perl
2787 5.14) turns on the given regular expression flags
2788 until the end of the lexical scope. See
2789 L<re/"'E<sol>flags' mode"> for more
2793 /^(.*)$/s; # output debugging info
2795 use re 'debugcolor';
2796 /^(.*)$/s; # output debugging info in living color
2798 The global C<debug> and C<debugcolor> pragmas allow one to get
2799 detailed debugging info about regexp compilation and
2800 execution. C<debugcolor> is the same as debug, except the debugging
2801 information is displayed in color on terminals that can display
2802 termcap color sequences. Here is example output:
2804 % perl -e 'use re "debug"; "abc" =~ /a*b+c/;'
2805 Compiling REx 'a*b+c'
2813 floating 'bc' at 0..2147483647 (checking floating) minlen 2
2814 Guessing start of match, REx 'a*b+c' against 'abc'...
2815 Found floating substr 'bc' at offset 1...
2816 Guessed: match at offset 0
2817 Matching REx 'a*b+c' against 'abc'
2818 Setting an EVAL scope, savestack=3
2819 0 <> <abc> | 1: STAR
2820 EXACT <a> can match 1 times out of 32767...
2821 Setting an EVAL scope, savestack=3
2822 1 <a> <bc> | 4: PLUS
2823 EXACT <b> can match 1 times out of 32767...
2824 Setting an EVAL scope, savestack=3
2825 2 <ab> <c> | 7: EXACT <c>
2828 Freeing REx: 'a*b+c'
2830 If you have gotten this far into the tutorial, you can probably guess
2831 what the different parts of the debugging output tell you. The first
2834 Compiling REx 'a*b+c'
2843 describes the compilation stage. C<STAR(4)> means that there is a
2844 starred object, in this case C<'a'>, and if it matches, goto line 4,
2845 i.e., C<PLUS(7)>. The middle lines describe some heuristics and
2846 optimizations performed before a match:
2848 floating 'bc' at 0..2147483647 (checking floating) minlen 2
2849 Guessing start of match, REx 'a*b+c' against 'abc'...
2850 Found floating substr 'bc' at offset 1...
2851 Guessed: match at offset 0
2853 Then the match is executed and the remaining lines describe the
2856 Matching REx 'a*b+c' against 'abc'
2857 Setting an EVAL scope, savestack=3
2858 0 <> <abc> | 1: STAR
2859 EXACT <a> can match 1 times out of 32767...
2860 Setting an EVAL scope, savestack=3
2861 1 <a> <bc> | 4: PLUS
2862 EXACT <b> can match 1 times out of 32767...
2863 Setting an EVAL scope, savestack=3
2864 2 <ab> <c> | 7: EXACT <c>
2867 Freeing REx: 'a*b+c'
2869 Each step is of the form S<C<< n <x> <y> >>>, with C<< <x> >> the
2870 part of the string matched and C<< <y> >> the part not yet
2871 matched. The S<C<< | 1: STAR >>> says that Perl is at line number 1
2872 in the compilation list above. See
2873 L<perldebguts/"Debugging Regular Expressions"> for much more detail.
2875 An alternative method of debugging regexps is to embed C<print>
2876 statements within the regexp. This provides a blow-by-blow account of
2877 the backtracking in an alternation:
2879 "that this" =~ m@(?{print "Start at position ", pos, "\n";})
2889 (?{print "Done at position ", pos, "\n";})
2905 Code expressions, conditional expressions, and independent expressions
2906 are I<experimental>. Don't use them in production code. Yet.
2910 This is just a tutorial. For the full story on Perl regular
2911 expressions, see the L<perlre> regular expressions reference page.
2913 For more information on the matching C<m//> and substitution C<s///>
2914 operators, see L<perlop/"Regexp Quote-Like Operators">. For
2915 information on the C<split> operation, see L<perlfunc/split>.
2917 For an excellent all-around resource on the care and feeding of
2918 regular expressions, see the book I<Mastering Regular Expressions> by
2919 Jeffrey Friedl (published by O'Reilly, ISBN 1556592-257-3).
2921 =head1 AUTHOR AND COPYRIGHT
2923 Copyright (c) 2000 Mark Kvale
2924 All rights reserved.
2926 This document may be distributed under the same terms as Perl itself.
2928 =head2 Acknowledgments
2930 The inspiration for the stop codon DNA example came from the ZIP
2931 code example in chapter 7 of I<Mastering Regular Expressions>.
2933 The author would like to thank Jeff Pinyan, Andrew Johnson, Peter
2934 Haworth, Ronald J Kimball, and Joe Smith for all their helpful