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

REVISION

1063       Revision: $Revision$
1064
1065       Date: $Date$
1066
1067       See perlfaq for source control details and availability.
1068
1070       Copyright (c) 1997-2009 Tom Christiansen, Nathan Torkington, and other
1071       authors as noted. All rights reserved.
1072
1073       This documentation is free; you can redistribute it and/or modify it
1074       under the same terms as Perl itself.
1075
1076       Irrespective of its distribution, all code examples in this file are
1077       hereby placed into the public domain.  You are permitted and encouraged
1078       to use this code in your own programs for fun or for profit as you see
1079       fit.  A simple comment in the code giving credit would be courteous but
1080       is not required.
1081
1082
1083
1084perl v5.10.1                      2009-08-15                       PERLFAQ6(1)
Impressum