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