1PERLFAQ6(1)            Perl Programmers Reference Guide            PERLFAQ6(1)
2
3
4

NAME

6       perlfaq6 - Regular Expressions
7

DESCRIPTION

9       This section is surprisingly small because the rest of the FAQ is
10       littered with answers involving regular expressions. For example,
11       decoding a URL and checking whether something is a number can be
12       handled with regular expressions, but those answers are found elsewhere
13       in this document (in perlfaq9: "How do I decode or create those
14       %-encodings on the web" and perlfaq4: "How do I determine whether a
15       scalar is a number/whole/integer/float", to be precise).
16
17   How can I hope to use regular expressions without creating illegible and
18       unmaintainable code?
19       Three techniques can make regular expressions maintainable and
20       understandable.
21
22       Comments Outside the Regex
23           Describe what you're doing and how you're doing it, using normal
24           Perl comments.
25
26               # turn the line into the first word, a colon, and the
27               # number of characters on the rest of the line
28               s/^(\w+)(.*)/ lc($1) . ":" . length($2) /meg;
29
30       Comments Inside the Regex
31           The "/x" modifier causes whitespace to be ignored in a regex
32           pattern (except in a character class and a few other places), and
33           also allows you to use normal comments there, too. As you can
34           imagine, whitespace and comments help a lot.
35
36           "/x" lets you turn this:
37
38               s{<(?:[^>'"]*|".*?"|'.*?')+>}{}gs;
39
40           into this:
41
42               s{ <                    # opening angle bracket
43                   (?:                 # Non-backreffing grouping paren
44                       [^>'"] *        # 0 or more things that are neither > nor ' nor "
45                           |           #    or else
46                       ".*?"           # a section between double quotes (stingy match)
47                           |           #    or else
48                       '.*?'           # a section between single quotes (stingy match)
49                   ) +                 #   all occurring one or more times
50                   >                   # closing angle bracket
51               }{}gsx;                 # replace with nothing, i.e. delete
52
53           It's still not quite so clear as prose, but it is very useful for
54           describing the meaning of each part of the pattern.
55
56       Different Delimiters
57           While we normally think of patterns as being delimited with "/"
58           characters, they can be delimited by almost any character. perlre
59           describes this. For example, the "s///" above uses braces as
60           delimiters. Selecting another delimiter can avoid quoting the
61           delimiter within the pattern:
62
63               s/\/usr\/local/\/usr\/share/g;    # bad delimiter choice
64               s#/usr/local#/usr/share#g;        # better
65
66           Using logically paired delimiters can be even more readable:
67
68               s{/usr/local/}{/usr/share}g;      # better still
69
70   I'm having trouble matching over more than one line. What's wrong?
71       Either you don't have more than one line in the string you're looking
72       at (probably), or else you aren't using the correct modifier(s) on your
73       pattern (possibly).
74
75       There are many ways to get multiline data into a string. If you want it
76       to happen automatically while reading input, you'll want to set $/
77       (probably to '' for paragraphs or "undef" for the whole file) to allow
78       you to read more than one line at a time.
79
80       Read perlre to help you decide which of "/s" and "/m" (or both) you
81       might want to use: "/s" allows dot to include newline, and "/m" allows
82       caret and dollar to match next to a newline, not just at the end of the
83       string. You do need to make sure that you've actually got a multiline
84       string in there.
85
86       For example, this program detects duplicate words, even when they span
87       line breaks (but not paragraph ones). For this example, we don't need
88       "/s" because we aren't using dot in a regular expression that we want
89       to cross line boundaries. Neither do we need "/m" because we don't want
90       caret or dollar to match at any point inside the record next to
91       newlines. But it's imperative that $/ be set to something other than
92       the default, or else we won't actually ever have a multiline record
93       read in.
94
95           $/ = '';          # read in whole paragraph, not just one line
96           while ( <> ) {
97               while ( /\b([\w'-]+)(\s+\g1)+\b/gi ) {     # word starts alpha
98                   print "Duplicate $1 at paragraph $.\n";
99               }
100           }
101
102       Here's some code that finds sentences that begin with "From " (which
103       would be mangled by many mailers):
104
105           $/ = '';          # read in whole paragraph, not just one line
106           while ( <> ) {
107               while ( /^From /gm ) { # /m makes ^ match next to \n
108               print "leading from in paragraph $.\n";
109               }
110           }
111
112       Here's code that finds everything between START and END in a paragraph:
113
114           undef $/;          # read in whole file, not just one line or paragraph
115           while ( <> ) {
116               while ( /START(.*?)END/sgm ) { # /s makes . cross line boundaries
117                   print "$1\n";
118               }
119           }
120
121   How can I pull out lines between two patterns that are themselves on
122       different lines?
123       You can use Perl's somewhat exotic ".." operator (documented in
124       perlop):
125
126           perl -ne 'print if /START/ .. /END/' file1 file2 ...
127
128       If you wanted text and not lines, you would use
129
130           perl -0777 -ne 'print "$1\n" while /START(.*?)END/gs' file1 file2 ...
131
132       But if you want nested occurrences of "START" through "END", you'll run
133       up against the problem described in the question in this section on
134       matching balanced text.
135
136       Here's another example of using "..":
137
138           while (<>) {
139               my $in_header =   1  .. /^$/;
140               my $in_body   = /^$/ .. eof;
141           # now choose between them
142           } continue {
143               $. = 0 if eof;    # fix $.
144           }
145
146   How do I match XML, HTML, or other nasty, ugly things with a regex?
147       Do not use regexes. Use a module and forget about the regular
148       expressions. The XML::LibXML, HTML::TokeParser and HTML::TreeBuilder
149       modules are good starts, although each namespace has other parsing
150       modules specialized for certain tasks and different ways of doing it.
151       Start at CPAN Search ( <http://metacpan.org/> ) and wonder at all the
152       work people have done for you already! :)
153
154   I put a regular expression into $/ but it didn't work. What's wrong?
155       $/ has to be a string. You can use these examples if you really need to
156       do this.
157
158       If you have File::Stream, this is easy.
159
160           use File::Stream;
161
162           my $stream = File::Stream->new(
163               $filehandle,
164               separator => qr/\s*,\s*/,
165               );
166
167           print "$_\n" while <$stream>;
168
169       If you don't have File::Stream, you have to do a little more work.
170
171       You can use the four-argument form of sysread to continually add to a
172       buffer. After you add to the buffer, you check if you have a complete
173       line (using your regular expression).
174
175           local $_ = "";
176           while( sysread FH, $_, 8192, length ) {
177               while( s/^((?s).*?)your_pattern// ) {
178                   my $record = $1;
179                   # do stuff here.
180               }
181           }
182
183       You can do the same thing with foreach and a match using the c flag and
184       the \G anchor, if you do not mind your entire file being in memory at
185       the end.
186
187           local $_ = "";
188           while( sysread FH, $_, 8192, length ) {
189               foreach my $record ( m/\G((?s).*?)your_pattern/gc ) {
190                   # do stuff here.
191               }
192               substr( $_, 0, pos ) = "" if pos;
193           }
194
195   How do I substitute case-insensitively on the LHS while preserving case on
196       the RHS?
197       Here's a lovely Perlish solution by Larry Rosler. It exploits
198       properties of bitwise xor on ASCII strings.
199
200           $_= "this is a TEsT case";
201
202           $old = 'test';
203           $new = 'success';
204
205           s{(\Q$old\E)}
206           { uc $new | (uc $1 ^ $1) .
207               (uc(substr $1, -1) ^ substr $1, -1) x
208               (length($new) - length $1)
209           }egi;
210
211           print;
212
213       And here it is as a subroutine, modeled after the above:
214
215           sub preserve_case($$) {
216               my ($old, $new) = @_;
217               my $mask = uc $old ^ $old;
218
219               uc $new | $mask .
220                   substr($mask, -1) x (length($new) - length($old))
221           }
222
223           $string = "this is a TEsT case";
224           $string =~ s/(test)/preserve_case($1, "success")/egi;
225           print "$string\n";
226
227       This prints:
228
229           this is a SUcCESS case
230
231       As an alternative, to keep the case of the replacement word if it is
232       longer than the original, you can use this code, by Jeff Pinyan:
233
234           sub preserve_case {
235               my ($from, $to) = @_;
236               my ($lf, $lt) = map length, @_;
237
238               if ($lt < $lf) { $from = substr $from, 0, $lt }
239               else { $from .= substr $to, $lf }
240
241               return uc $to | ($from ^ uc $from);
242           }
243
244       This changes the sentence to "this is a SUcCess case."
245
246       Just to show that C programmers can write C in any programming
247       language, if you prefer a more C-like solution, the following script
248       makes the substitution have the same case, letter by letter, as the
249       original.  (It also happens to run about 240% slower than the Perlish
250       solution runs.)  If the substitution has more characters than the
251       string being substituted, the case of the last character is used for
252       the rest of the substitution.
253
254           # Original by Nathan Torkington, massaged by Jeffrey Friedl
255           #
256           sub preserve_case($$)
257           {
258               my ($old, $new) = @_;
259               my $state = 0; # 0 = no change; 1 = lc; 2 = uc
260               my ($i, $oldlen, $newlen, $c) = (0, length($old), length($new));
261               my $len = $oldlen < $newlen ? $oldlen : $newlen;
262
263               for ($i = 0; $i < $len; $i++) {
264                   if ($c = substr($old, $i, 1), $c =~ /[\W\d_]/) {
265                       $state = 0;
266                   } elsif (lc $c eq $c) {
267                       substr($new, $i, 1) = lc(substr($new, $i, 1));
268                       $state = 1;
269                   } else {
270                       substr($new, $i, 1) = uc(substr($new, $i, 1));
271                       $state = 2;
272                   }
273               }
274               # finish up with any remaining new (for when new is longer than old)
275               if ($newlen > $oldlen) {
276                   if ($state == 1) {
277                       substr($new, $oldlen) = lc(substr($new, $oldlen));
278                   } elsif ($state == 2) {
279                       substr($new, $oldlen) = uc(substr($new, $oldlen));
280                   }
281               }
282               return $new;
283           }
284
285   How can I make "\w" match national character sets?
286       Put "use locale;" in your script. The \w character class is taken from
287       the current locale.
288
289       See perllocale for details.
290
291   How can I match a locale-smart version of "/[a-zA-Z]/"?
292       You can use the POSIX character class syntax "/[[:alpha:]]/" documented
293       in perlre.
294
295       No matter which locale you are in, the alphabetic characters are the
296       characters in \w without the digits and the underscore.  As a regex,
297       that looks like "/[^\W\d_]/". Its complement, the non-alphabetics, is
298       then everything in \W along with the digits and the underscore, or
299       "/[\W\d_]/".
300
301   How can I quote a variable to use in a regex?
302       The Perl parser will expand $variable and @variable references in
303       regular expressions unless the delimiter is a single quote. Remember,
304       too, that the right-hand side of a "s///" substitution is considered a
305       double-quoted string (see perlop for more details). Remember also that
306       any regex special characters will be acted on unless you precede the
307       substitution with \Q. Here's an example:
308
309           $string = "Placido P. Octopus";
310           $regex  = "P.";
311
312           $string =~ s/$regex/Polyp/;
313           # $string is now "Polypacido P. Octopus"
314
315       Because "." is special in regular expressions, and can match any single
316       character, the regex "P." here has matched the <Pl> in the original
317       string.
318
319       To escape the special meaning of ".", we use "\Q":
320
321           $string = "Placido P. Octopus";
322           $regex  = "P.";
323
324           $string =~ s/\Q$regex/Polyp/;
325           # $string is now "Placido Polyp Octopus"
326
327       The use of "\Q" causes the <.> in the regex to be treated as a regular
328       character, so that "P." matches a "P" followed by a dot.
329
330   What is "/o" really for?
331       (contributed by brian d foy)
332
333       The "/o" option for regular expressions (documented in perlop and
334       perlreref) tells Perl to compile the regular expression only once.
335       This is only useful when the pattern contains a variable. Perls 5.6 and
336       later handle this automatically if the pattern does not change.
337
338       Since the match operator "m//", the substitution operator "s///", and
339       the regular expression quoting operator "qr//" are double-quotish
340       constructs, you can interpolate variables into the pattern. See the
341       answer to "How can I quote a variable to use in a regex?" for more
342       details.
343
344       This example takes a regular expression from the argument list and
345       prints the lines of input that match it:
346
347           my $pattern = shift @ARGV;
348
349           while( <> ) {
350               print if m/$pattern/;
351           }
352
353       Versions of Perl prior to 5.6 would recompile the regular expression
354       for each iteration, even if $pattern had not changed. The "/o" would
355       prevent this by telling Perl to compile the pattern the first time,
356       then reuse that for subsequent iterations:
357
358           my $pattern = shift @ARGV;
359
360           while( <> ) {
361               print if m/$pattern/o; # useful for Perl < 5.6
362           }
363
364       In versions 5.6 and later, Perl won't recompile the regular expression
365       if the variable hasn't changed, so you probably don't need the "/o"
366       option. It doesn't hurt, but it doesn't help either. If you want any
367       version of Perl to compile the regular expression only once even if the
368       variable changes (thus, only using its initial value), you still need
369       the "/o".
370
371       You can watch Perl's regular expression engine at work to verify for
372       yourself if Perl is recompiling a regular expression. The "use re
373       'debug'" pragma (comes with Perl 5.005 and later) shows the details.
374       With Perls before 5.6, you should see "re" reporting that its compiling
375       the regular expression on each iteration. With Perl 5.6 or later, you
376       should only see "re" report that for the first iteration.
377
378           use re 'debug';
379
380           my $regex = 'Perl';
381           foreach ( qw(Perl Java Ruby Python) ) {
382               print STDERR "-" x 73, "\n";
383               print STDERR "Trying $_...\n";
384               print STDERR "\t$_ is good!\n" if m/$regex/;
385           }
386
387   How do I use a regular expression to strip C-style comments from a file?
388       While this actually can be done, it's much harder than you'd think.
389       For example, this one-liner
390
391           perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c
392
393       will work in many but not all cases. You see, it's too simple-minded
394       for certain kinds of C programs, in particular, those with what appear
395       to be comments in quoted strings. For that, you'd need something like
396       this, created by Jeffrey Friedl and later modified by Fred Curtis.
397
398           $/ = undef;
399           $_ = <>;
400           s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $2 ? $2 : ""#gse;
401           print;
402
403       This could, of course, be more legibly written with the "/x" modifier,
404       adding whitespace and comments. Here it is expanded, courtesy of Fred
405       Curtis.
406
407           s{
408              /\*         ##  Start of /* ... */ comment
409              [^*]*\*+    ##  Non-* followed by 1-or-more *'s
410              (
411                [^/*][^*]*\*+
412              )*          ##  0-or-more things which don't start with /
413                          ##    but do end with '*'
414              /           ##  End of /* ... */ comment
415
416            |         ##     OR  various things which aren't comments:
417
418              (
419                "           ##  Start of " ... " string
420                (
421                  \\.           ##  Escaped char
422                |               ##    OR
423                  [^"\\]        ##  Non "\
424                )*
425                "           ##  End of " ... " string
426
427              |         ##     OR
428
429                '           ##  Start of ' ... ' string
430                (
431                  \\.           ##  Escaped char
432                |               ##    OR
433                  [^'\\]        ##  Non '\
434                )*
435                '           ##  End of ' ... ' string
436
437              |         ##     OR
438
439                .           ##  Anything other char
440                [^/"'\\]*   ##  Chars which doesn't start a comment, string or escape
441              )
442            }{defined $2 ? $2 : ""}gxse;
443
444       A slight modification also removes C++ comments, possibly spanning
445       multiple lines using a continuation character:
446
447        s#/\*[^*]*\*+([^/*][^*]*\*+)*/|//([^\\]|[^\n][\n]?)*?\n|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $3 ? $3 : ""#gse;
448
449   Can I use Perl regular expressions to match balanced text?
450       (contributed by brian d foy)
451
452       Your first try should probably be the Text::Balanced module, which is
453       in the Perl standard library since Perl 5.8. It has a variety of
454       functions to deal with tricky text. The Regexp::Common module can also
455       help by providing canned patterns you can use.
456
457       As of Perl 5.10, you can match balanced text with regular expressions
458       using recursive patterns. Before Perl 5.10, you had to resort to
459       various tricks such as using Perl code in "(??{})" sequences.
460
461       Here's an example using a recursive regular expression. The goal is to
462       capture all of the text within angle brackets, including the text in
463       nested angle brackets. This sample text has two "major" groups: a group
464       with one level of nesting and a group with two levels of nesting. There
465       are five total groups in angle brackets:
466
467           I have some <brackets in <nested brackets> > and
468           <another group <nested once <nested twice> > >
469           and that's it.
470
471       The regular expression to match the balanced text uses two new (to Perl
472       5.10) regular expression features. These are covered in perlre and this
473       example is a modified version of one in that documentation.
474
475       First, adding the new possessive "+" to any quantifier finds the
476       longest match and does not backtrack. That's important since you want
477       to handle any angle brackets through the recursion, not backtracking.
478       The group "[^<>]++" finds one or more non-angle brackets without
479       backtracking.
480
481       Second, the new "(?PARNO)" refers to the sub-pattern in the particular
482       capture group given by "PARNO". In the following regex, the first
483       capture group finds (and remembers) the balanced text, and you need
484       that same pattern within the first buffer to get past the nested text.
485       That's the recursive part. The "(?1)" uses the pattern in the outer
486       capture group as an independent part of the regex.
487
488       Putting it all together, you have:
489
490           #!/usr/local/bin/perl5.10.0
491
492           my $string =<<"HERE";
493           I have some <brackets in <nested brackets> > and
494           <another group <nested once <nested twice> > >
495           and that's it.
496           HERE
497
498           my @groups = $string =~ m/
499                   (                   # start of capture group 1
500                   <                   # match an opening angle bracket
501                       (?:
502                           [^<>]++     # one or more non angle brackets, non backtracking
503                             |
504                           (?1)        # found < or >, so recurse to capture group 1
505                       )*
506                   >                   # match a closing angle bracket
507                   )                   # end of capture group 1
508                   /xg;
509
510           $" = "\n\t";
511           print "Found:\n\t@groups\n";
512
513       The output shows that Perl found the two major groups:
514
515           Found:
516               <brackets in <nested brackets> >
517               <another group <nested once <nested twice> > >
518
519       With a little extra work, you can get the all of the groups in angle
520       brackets even if they are in other angle brackets too. Each time you
521       get a balanced match, remove its outer delimiter (that's the one you
522       just matched so don't match it again) and add it to a queue of strings
523       to process. Keep doing that until you get no matches:
524
525           #!/usr/local/bin/perl5.10.0
526
527           my @queue =<<"HERE";
528           I have some <brackets in <nested brackets> > and
529           <another group <nested once <nested twice> > >
530           and that's it.
531           HERE
532
533           my $regex = qr/
534                   (                   # start of bracket 1
535                   <                   # match an opening angle bracket
536                       (?:
537                           [^<>]++     # one or more non angle brackets, non backtracking
538                             |
539                           (?1)        # recurse to bracket 1
540                       )*
541                   >                   # match a closing angle bracket
542                   )                   # end of bracket 1
543                   /x;
544
545           $" = "\n\t";
546
547           while( @queue ) {
548               my $string = shift @queue;
549
550               my @groups = $string =~ m/$regex/g;
551               print "Found:\n\t@groups\n\n" if @groups;
552
553               unshift @queue, map { s/^<//; s/>$//; $_ } @groups;
554           }
555
556       The output shows all of the groups. The outermost matches show up first
557       and the nested matches so up later:
558
559           Found:
560               <brackets in <nested brackets> >
561               <another group <nested once <nested twice> > >
562
563           Found:
564               <nested brackets>
565
566           Found:
567               <nested once <nested twice> >
568
569           Found:
570               <nested twice>
571
572   What does it mean that regexes are greedy? How can I get around it?
573       Most people mean that greedy regexes match as much as they can.
574       Technically speaking, it's actually the quantifiers ("?", "*", "+",
575       "{}") that are greedy rather than the whole pattern; Perl prefers local
576       greed and immediate gratification to overall greed. To get non-greedy
577       versions of the same quantifiers, use ("??", "*?", "+?", "{}?").
578
579       An example:
580
581           my $s1 = my $s2 = "I am very very cold";
582           $s1 =~ s/ve.*y //;      # I am cold
583           $s2 =~ s/ve.*?y //;     # I am very cold
584
585       Notice how the second substitution stopped matching as soon as it
586       encountered "y ". The "*?" quantifier effectively tells the regular
587       expression engine to find a match as quickly as possible and pass
588       control on to whatever is next in line, as you would if you were
589       playing hot potato.
590
591   How do I process each word on each line?
592       Use the split function:
593
594           while (<>) {
595               foreach my $word ( split ) {
596                   # do something with $word here
597               }
598           }
599
600       Note that this isn't really a word in the English sense; it's just
601       chunks of consecutive non-whitespace characters.
602
603       To work with only alphanumeric sequences (including underscores), you
604       might consider
605
606           while (<>) {
607               foreach $word (m/(\w+)/g) {
608                   # do something with $word here
609               }
610           }
611
612   How can I print out a word-frequency or line-frequency summary?
613       To do this, you have to parse out each word in the input stream. We'll
614       pretend that by word you mean chunk of alphabetics, hyphens, or
615       apostrophes, rather than the non-whitespace chunk idea of a word given
616       in the previous question:
617
618           my (%seen);
619           while (<>) {
620               while ( /(\b[^\W_\d][\w'-]+\b)/g ) {   # misses "`sheep'"
621                   $seen{$1}++;
622               }
623           }
624
625           while ( my ($word, $count) = each %seen ) {
626               print "$count $word\n";
627           }
628
629       If you wanted to do the same thing for lines, you wouldn't need a
630       regular expression:
631
632           my (%seen);
633
634           while (<>) {
635               $seen{$_}++;
636           }
637
638           while ( my ($line, $count) = each %seen ) {
639               print "$count $line";
640           }
641
642       If you want these output in a sorted order, see perlfaq4: "How do I
643       sort a hash (optionally by value instead of key)?".
644
645   How can I do approximate matching?
646       See the module String::Approx available from CPAN.
647
648   How do I efficiently match many regular expressions at once?
649       (contributed by brian d foy)
650
651       If you have Perl 5.10 or later, this is almost trivial. You just smart
652       match against an array of regular expression objects:
653
654           my @patterns = ( qr/Fr.d/, qr/B.rn.y/, qr/W.lm./ );
655
656           if( $string ~~ @patterns ) {
657               ...
658           };
659
660       The smart match stops when it finds a match, so it doesn't have to try
661       every expression.
662
663       Earlier than Perl 5.10, you have a bit of work to do. You want to avoid
664       compiling a regular expression every time you want to match it.  In
665       this example, perl must recompile the regular expression for every
666       iteration of the "foreach" loop since it has no way to know what
667       $pattern will be:
668
669           my @patterns = qw( foo bar baz );
670
671           LINE: while( <DATA> ) {
672               foreach $pattern ( @patterns ) {
673                   if( /\b$pattern\b/i ) {
674                       print;
675                       next LINE;
676                   }
677               }
678           }
679
680       The "qr//" operator showed up in perl 5.005. It compiles a regular
681       expression, but doesn't apply it. When you use the pre-compiled version
682       of the regex, perl does less work. In this example, I inserted a "map"
683       to turn each pattern into its pre-compiled form. The rest of the script
684       is the same, but faster:
685
686           my @patterns = map { qr/\b$_\b/i } qw( foo bar baz );
687
688           LINE: while( <> ) {
689               foreach $pattern ( @patterns ) {
690                   if( /$pattern/ ) {
691                       print;
692                       next LINE;
693                   }
694               }
695           }
696
697       In some cases, you may be able to make several patterns into a single
698       regular expression. Beware of situations that require backtracking
699       though.
700
701           my $regex = join '|', qw( foo bar baz );
702
703           LINE: while( <> ) {
704               print if /\b(?:$regex)\b/i;
705           }
706
707       For more details on regular expression efficiency, see Mastering
708       Regular Expressions by Jeffrey Friedl. He explains how the regular
709       expressions engine works and why some patterns are surprisingly
710       inefficient. Once you understand how perl applies regular expressions,
711       you can tune them for individual situations.
712
713   Why don't word-boundary searches with "\b" work for me?
714       (contributed by brian d foy)
715
716       Ensure that you know what \b really does: it's the boundary between a
717       word character, \w, and something that isn't a word character. That
718       thing that isn't a word character might be \W, but it can also be the
719       start or end of the string.
720
721       It's not (not!) the boundary between whitespace and non-whitespace, and
722       it's not the stuff between words we use to create sentences.
723
724       In regex speak, a word boundary (\b) is a "zero width assertion",
725       meaning that it doesn't represent a character in the string, but a
726       condition at a certain position.
727
728       For the regular expression, /\bPerl\b/, there has to be a word boundary
729       before the "P" and after the "l". As long as something other than a
730       word character precedes the "P" and succeeds the "l", the pattern will
731       match. These strings match /\bPerl\b/.
732
733           "Perl"    # no word char before P or after l
734           "Perl "   # same as previous (space is not a word char)
735           "'Perl'"  # the ' char is not a word char
736           "Perl's"  # no word char before P, non-word char after "l"
737
738       These strings do not match /\bPerl\b/.
739
740           "Perl_"   # _ is a word char!
741           "Perler"  # no word char before P, but one after l
742
743       You don't have to use \b to match words though. You can look for non-
744       word characters surrounded by word characters. These strings match the
745       pattern /\b'\b/.
746
747           "don't"   # the ' char is surrounded by "n" and "t"
748           "qep'a'"  # the ' char is surrounded by "p" and "a"
749
750       These strings do not match /\b'\b/.
751
752           "foo'"    # there is no word char after non-word '
753
754       You can also use the complement of \b, \B, to specify that there should
755       not be a word boundary.
756
757       In the pattern /\Bam\B/, there must be a word character before the "a"
758       and after the "m". These patterns match /\Bam\B/:
759
760           "llama"   # "am" surrounded by word chars
761           "Samuel"  # same
762
763       These strings do not match /\Bam\B/
764
765           "Sam"      # no word boundary before "a", but one after "m"
766           "I am Sam" # "am" surrounded by non-word chars
767
768   Why does using $&, $`, or $' slow my program down?
769       (contributed by Anno Siegel)
770
771       Once Perl sees that you need one of these variables anywhere in the
772       program, it provides them on each and every pattern match. That means
773       that on every pattern match the entire string will be copied, part of
774       it to $`, part to $&, and part to $'. Thus the penalty is most severe
775       with long strings and patterns that match often. Avoid $&, $', and $`
776       if you can, but if you can't, once you've used them at all, use them at
777       will because you've already paid the price. Remember that some
778       algorithms really appreciate them. As of the 5.005 release, the $&
779       variable is no longer "expensive" the way the other two are.
780
781       Since Perl 5.6.1 the special variables @- and @+ can functionally
782       replace $`, $& and $'. These arrays contain pointers to the beginning
783       and end of each match (see perlvar for the full story), so they give
784       you essentially the same information, but without the risk of excessive
785       string copying.
786
787       Perl 5.10 added three specials, "${^MATCH}", "${^PREMATCH}", and
788       "${^POSTMATCH}" to do the same job but without the global performance
789       penalty. Perl 5.10 only sets these variables if you compile or execute
790       the regular expression with the "/p" modifier.
791
792   What good is "\G" in a regular expression?
793       You use the "\G" anchor to start the next match on the same string
794       where the last match left off. The regular expression engine cannot
795       skip over any characters to find the next match with this anchor, so
796       "\G" is similar to the beginning of string anchor, "^". The "\G" anchor
797       is typically used with the "g" flag. It uses the value of "pos()" as
798       the position to start the next match. As the match operator makes
799       successive matches, it updates "pos()" with the position of the next
800       character past the last match (or the first character of the next
801       match, depending on how you like to look at it). Each string has its
802       own "pos()" value.
803
804       Suppose you want to match all of consecutive pairs of digits in a
805       string like "1122a44" and stop matching when you encounter non-digits.
806       You want to match 11 and 22 but the letter <a> shows up between 22 and
807       44 and you want to stop at "a". Simply matching pairs of digits skips
808       over the "a" and still matches 44.
809
810           $_ = "1122a44";
811           my @pairs = m/(\d\d)/g;   # qw( 11 22 44 )
812
813       If you use the "\G" anchor, you force the match after 22 to start with
814       the "a". The regular expression cannot match there since it does not
815       find a digit, so the next match fails and the match operator returns
816       the pairs it already found.
817
818           $_ = "1122a44";
819           my @pairs = m/\G(\d\d)/g; # qw( 11 22 )
820
821       You can also use the "\G" anchor in scalar context. You still need the
822       "g" flag.
823
824           $_ = "1122a44";
825           while( m/\G(\d\d)/g ) {
826               print "Found $1\n";
827           }
828
829       After the match fails at the letter "a", perl resets "pos()" and the
830       next match on the same string starts at the beginning.
831
832           $_ = "1122a44";
833           while( m/\G(\d\d)/g ) {
834               print "Found $1\n";
835           }
836
837           print "Found $1 after while" if m/(\d\d)/g; # finds "11"
838
839       You can disable "pos()" resets on fail with the "c" flag, documented in
840       perlop and perlreref. Subsequent matches start where the last
841       successful match ended (the value of "pos()") even if a match on the
842       same string has failed in the meantime. In this case, the match after
843       the "while()" loop starts at the "a" (where the last match stopped),
844       and since it does not use any anchor it can skip over the "a" to find
845       44.
846
847           $_ = "1122a44";
848           while( m/\G(\d\d)/gc ) {
849               print "Found $1\n";
850           }
851
852           print "Found $1 after while" if m/(\d\d)/g; # finds "44"
853
854       Typically you use the "\G" anchor with the "c" flag when you want to
855       try a different match if one fails, such as in a tokenizer. Jeffrey
856       Friedl offers this example which works in 5.004 or later.
857
858           while (<>) {
859               chomp;
860               PARSER: {
861                   m/ \G( \d+\b    )/gcx   && do { print "number: $1\n";  redo; };
862                   m/ \G( \w+      )/gcx   && do { print "word:   $1\n";  redo; };
863                   m/ \G( \s+      )/gcx   && do { print "space:  $1\n";  redo; };
864                   m/ \G( [^\w\d]+ )/gcx   && do { print "other:  $1\n";  redo; };
865               }
866           }
867
868       For each line, the "PARSER" loop first tries to match a series of
869       digits followed by a word boundary. This match has to start at the
870       place the last match left off (or the beginning of the string on the
871       first match). Since "m/ \G( \d+\b )/gcx" uses the "c" flag, if the
872       string does not match that regular expression, perl does not reset
873       pos() and the next match starts at the same position to try a different
874       pattern.
875
876   Are Perl regexes DFAs or NFAs? Are they POSIX compliant?
877       While it's true that Perl's regular expressions resemble the DFAs
878       (deterministic finite automata) of the egrep(1) program, they are in
879       fact implemented as NFAs (non-deterministic finite automata) to allow
880       backtracking and backreferencing. And they aren't POSIX-style either,
881       because those guarantee worst-case behavior for all cases. (It seems
882       that some people prefer guarantees of consistency, even when what's
883       guaranteed is slowness.) See the book "Mastering Regular Expressions"
884       (from O'Reilly) by Jeffrey Friedl for all the details you could ever
885       hope to know on these matters (a full citation appears in perlfaq2).
886
887   What's wrong with using grep in a void context?
888       The problem is that grep builds a return list, regardless of the
889       context.  This means you're making Perl go to the trouble of building a
890       list that you then just throw away. If the list is large, you waste
891       both time and space.  If your intent is to iterate over the list, then
892       use a for loop for this purpose.
893
894       In perls older than 5.8.1, map suffers from this problem as well.  But
895       since 5.8.1, this has been fixed, and map is context aware - in void
896       context, no lists are constructed.
897
898   How can I match strings with multibyte characters?
899       Starting from Perl 5.6 Perl has had some level of multibyte character
900       support. Perl 5.8 or later is recommended. Supported multibyte
901       character repertoires include Unicode, and legacy encodings through the
902       Encode module. See perluniintro, perlunicode, and Encode.
903
904       If you are stuck with older Perls, you can do Unicode with the
905       Unicode::String module, and character conversions using the
906       Unicode::Map8 and Unicode::Map modules. If you are using Japanese
907       encodings, you might try using the jperl 5.005_03.
908
909       Finally, the following set of approaches was offered by Jeffrey Friedl,
910       whose article in issue #5 of The Perl Journal talks about this very
911       matter.
912
913       Let's suppose you have some weird Martian encoding where pairs of ASCII
914       uppercase letters encode single Martian letters (i.e. the two bytes
915       "CV" make a single Martian letter, as do the two bytes "SG", "VS",
916       "XX", etc.). Other bytes represent single characters, just like ASCII.
917
918       So, the string of Martian "I am CVSGXX!" uses 12 bytes to encode the
919       nine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.
920
921       Now, say you want to search for the single character "/GX/". Perl
922       doesn't know about Martian, so it'll find the two bytes "GX" in the "I
923       am CVSGXX!" string, even though that character isn't there: it just
924       looks like it is because "SG" is next to "XX", but there's no real
925       "GX". This is a big problem.
926
927       Here are a few ways, all painful, to deal with it:
928
929           # Make sure adjacent "martian" bytes are no longer adjacent.
930           $martian =~ s/([A-Z][A-Z])/ $1 /g;
931
932           print "found GX!\n" if $martian =~ /GX/;
933
934       Or like this:
935
936           my @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;
937           # above is conceptually similar to:     my @chars = $text =~ m/(.)/g;
938           #
939           foreach my $char (@chars) {
940               print "found GX!\n", last if $char eq 'GX';
941           }
942
943       Or like this:
944
945           while ($martian =~ m/\G([A-Z][A-Z]|.)/gs) {  # \G probably unneeded
946               if ($1 eq 'GX') {
947                   print "found GX!\n";
948                   last;
949               }
950           }
951
952       Here's another, slightly less painful, way to do it from Benjamin
953       Goldberg, who uses a zero-width negative look-behind assertion.
954
955           print "found GX!\n" if    $martian =~ m/
956               (?<![A-Z])
957               (?:[A-Z][A-Z])*?
958               GX
959               /x;
960
961       This succeeds if the "martian" character GX is in the string, and fails
962       otherwise. If you don't like using (?<!), a zero-width negative look-
963       behind assertion, you can replace (?<![A-Z]) with (?:^|[^A-Z]).
964
965       It does have the drawback of putting the wrong thing in $-[0] and
966       $+[0], but this usually can be worked around.
967
968   How do I match a regular expression that's in a variable?
969       (contributed by brian d foy)
970
971       We don't have to hard-code patterns into the match operator (or
972       anything else that works with regular expressions). We can put the
973       pattern in a variable for later use.
974
975       The match operator is a double quote context, so you can interpolate
976       your variable just like a double quoted string. In this case, you read
977       the regular expression as user input and store it in $regex.  Once you
978       have the pattern in $regex, you use that variable in the match
979       operator.
980
981           chomp( my $regex = <STDIN> );
982
983           if( $string =~ m/$regex/ ) { ... }
984
985       Any regular expression special characters in $regex are still special,
986       and the pattern still has to be valid or Perl will complain.  For
987       instance, in this pattern there is an unpaired parenthesis.
988
989           my $regex = "Unmatched ( paren";
990
991           "Two parens to bind them all" =~ m/$regex/;
992
993       When Perl compiles the regular expression, it treats the parenthesis as
994       the start of a memory match. When it doesn't find the closing
995       parenthesis, it complains:
996
997           Unmatched ( in regex; marked by <-- HERE in m/Unmatched ( <-- HERE  paren/ at script line 3.
998
999       You can get around this in several ways depending on our situation.
1000       First, if you don't want any of the characters in the string to be
1001       special, you can escape them with "quotemeta" before you use the
1002       string.
1003
1004           chomp( my $regex = <STDIN> );
1005           $regex = quotemeta( $regex );
1006
1007           if( $string =~ m/$regex/ ) { ... }
1008
1009       You can also do this directly in the match operator using the "\Q" and
1010       "\E" sequences. The "\Q" tells Perl where to start escaping special
1011       characters, and the "\E" tells it where to stop (see perlop for more
1012       details).
1013
1014           chomp( my $regex = <STDIN> );
1015
1016           if( $string =~ m/\Q$regex\E/ ) { ... }
1017
1018       Alternately, you can use "qr//", the regular expression quote operator
1019       (see perlop for more details). It quotes and perhaps compiles the
1020       pattern, and you can apply regular expression flags to the pattern.
1021
1022           chomp( my $input = <STDIN> );
1023
1024           my $regex = qr/$input/is;
1025
1026           $string =~ m/$regex/  # same as m/$input/is;
1027
1028       You might also want to trap any errors by wrapping an "eval" block
1029       around the whole thing.
1030
1031           chomp( my $input = <STDIN> );
1032
1033           eval {
1034               if( $string =~ m/\Q$input\E/ ) { ... }
1035           };
1036           warn $@ if $@;
1037
1038       Or...
1039
1040           my $regex = eval { qr/$input/is };
1041           if( defined $regex ) {
1042               $string =~ m/$regex/;
1043           }
1044           else {
1045               warn $@;
1046           }
1047
1049       Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other
1050       authors as noted. All rights reserved.
1051
1052       This documentation is free; you can redistribute it and/or modify it
1053       under the same terms as Perl itself.
1054
1055       Irrespective of its distribution, all code examples in this file are
1056       hereby placed into the public domain. You are permitted and encouraged
1057       to use this code in your own programs for fun or for profit as you see
1058       fit. A simple comment in the code giving credit would be courteous but
1059       is not required.
1060
1061
1062
1063perl v5.16.3                      2013-03-04                       PERLFAQ6(1)
Impressum