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