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 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   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, besieged 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 possessive "+" to any quantifier finds the
499       longest match and does not backtrack. That's important since you want
500       to handle any angle brackets through the recursion, not backtracking.
501       The group "[^<>]++" finds one or more non-angle brackets without
502       backtracking.
503
504       Second, the new "(?PARNO)" refers to the sub-pattern in the particular
505       capture buffer given by "PARNO". In the following regex, the first
506       capture buffer finds (and remembers) the balanced text, and you  need
507       that same pattern within the first buffer to get past the nested text.
508       That's the recursive part. The "(?1)" uses the pattern in the outer
509       capture buffer as an independent part of the regex.
510
511       Putting it all together, you have:
512
513               #!/usr/local/bin/perl5.10.0
514
515               my $string =<<"HERE";
516               I have some <brackets in <nested brackets> > and
517               <another group <nested once <nested twice> > >
518               and that's it.
519               HERE
520
521               my @groups = $string =~ m/
522                               (                   # start of capture buffer 1
523                               <                   # match an opening angle bracket
524                                       (?:
525                                               [^<>]++     # one or more non angle brackets, non backtracking
526                                                 |
527                                               (?1)        # found < or >, so recurse to capture buffer 1
528                                       )*
529                               >                   # match a closing angle bracket
530                               )                   # end of capture buffer 1
531                               /xg;
532
533               $" = "\n\t";
534               print "Found:\n\t@groups\n";
535
536       The output shows that Perl found the two major groups:
537
538               Found:
539                       <brackets in <nested brackets> >
540                       <another group <nested once <nested twice> > >
541
542       With a little extra work, you can get the all of the groups in angle
543       brackets even if they are in other angle brackets too. Each time you
544       get a balanced match, remove its outer delimiter (that's the one you
545       just matched so don't match it again) and add it to a queue of strings
546       to process. Keep doing that until you get no matches:
547
548               #!/usr/local/bin/perl5.10.0
549
550               my @queue =<<"HERE";
551               I have some <brackets in <nested brackets> > and
552               <another group <nested once <nested twice> > >
553               and that's it.
554               HERE
555
556               my $regex = qr/
557                               (                   # start of bracket 1
558                               <                   # match an opening angle bracket
559                                       (?:
560                                               [^<>]++     # one or more non angle brackets, non backtracking
561                                                 |
562                                               (?1)        # recurse to bracket 1
563                                       )*
564                               >                   # match a closing angle bracket
565                               )                   # end of bracket 1
566                               /x;
567
568               $" = "\n\t";
569
570               while( @queue )
571                       {
572                       my $string = shift @queue;
573
574                       my @groups = $string =~ m/$regex/g;
575                       print "Found:\n\t@groups\n\n" if @groups;
576
577                       unshift @queue, map { s/^<//; s/>$//; $_ } @groups;
578                       }
579
580       The output shows all of the groups. The outermost matches show up first
581       and the nested matches so up later:
582
583               Found:
584                       <brackets in <nested brackets> >
585                       <another group <nested once <nested twice> > >
586
587               Found:
588                       <nested brackets>
589
590               Found:
591                       <nested once <nested twice> >
592
593               Found:
594                       <nested twice>
595
596   What does it mean that regexes are greedy?  How can I get around it?
597       Most people mean that greedy regexes match as much as they can.
598       Technically speaking, it's actually the quantifiers ("?", "*", "+",
599       "{}") that are greedy rather than the whole pattern; Perl prefers local
600       greed and immediate gratification to overall greed.  To get non-greedy
601       versions of the same quantifiers, use ("??", "*?", "+?", "{}?").
602
603       An example:
604
605               $s1 = $s2 = "I am very very cold";
606               $s1 =~ s/ve.*y //;      # I am cold
607               $s2 =~ s/ve.*?y //;     # I am very cold
608
609       Notice how the second substitution stopped matching as soon as it
610       encountered "y ".  The "*?" quantifier effectively tells the regular
611       expression engine to find a match as quickly as possible and pass
612       control on to whatever is next in line, like you would if you were
613       playing hot potato.
614
615   How do I process each word on each line?
616       Use the split function:
617
618               while (<>) {
619                       foreach $word ( split ) {
620                               # do something with $word here
621                       }
622               }
623
624       Note that this isn't really a word in the English sense; it's just
625       chunks of consecutive non-whitespace characters.
626
627       To work with only alphanumeric sequences (including underscores), you
628       might consider
629
630               while (<>) {
631                       foreach $word (m/(\w+)/g) {
632                               # do something with $word here
633                       }
634               }
635
636   How can I print out a word-frequency or line-frequency summary?
637       To do this, you have to parse out each word in the input stream.  We'll
638       pretend that by word you mean chunk of alphabetics, hyphens, or
639       apostrophes, rather than the non-whitespace chunk idea of a word given
640       in the previous question:
641
642               while (<>) {
643                       while ( /(\b[^\W_\d][\w'-]+\b)/g ) {   # misses "`sheep'"
644                               $seen{$1}++;
645                       }
646               }
647
648               while ( ($word, $count) = each %seen ) {
649                       print "$count $word\n";
650                       }
651
652       If you wanted to do the same thing for lines, you wouldn't need a
653       regular expression:
654
655               while (<>) {
656                       $seen{$_}++;
657                       }
658
659               while ( ($line, $count) = each %seen ) {
660                       print "$count $line";
661               }
662
663       If you want these output in a sorted order, see perlfaq4: "How do I
664       sort a hash (optionally by value instead of key)?".
665
666   How can I do approximate matching?
667       See the module String::Approx available from CPAN.
668
669   How do I efficiently match many regular expressions at once?
670       ( contributed by brian d foy )
671
672       Avoid asking Perl to compile a regular expression every time you want
673       to match it. In this example, perl must recompile the regular
674       expression for every iteration of the "foreach" loop since it has no
675       way to know what $pattern will be.
676
677               @patterns = qw( foo bar baz );
678
679               LINE: while( <DATA> )
680                       {
681                       foreach $pattern ( @patterns )
682                               {
683                               if( /\b$pattern\b/i )
684                                       {
685                                       print;
686                                       next LINE;
687                                       }
688                               }
689                       }
690
691       The "qr//" operator showed up in perl 5.005.  It compiles a regular
692       expression, but doesn't apply it.  When you use the pre-compiled
693       version of the regex, perl does less work. In this example, I inserted
694       a "map" to turn each pattern into its pre-compiled form. The rest of
695       the script is the same, but faster.
696
697               @patterns = map { qr/\b$_\b/i } qw( foo bar baz );
698
699               LINE: while( <> )
700                       {
701                       foreach $pattern ( @patterns )
702                               {
703                               if( /$pattern/ )
704                                       {
705                                       print;
706                                       next LINE;
707                                       }
708                               }
709                       }
710
711       In some cases, you may be able to make several patterns into a single
712       regular expression. Beware of situations that require backtracking
713       though.
714
715               $regex = join '|', qw( foo bar baz );
716
717               LINE: while( <> )
718                       {
719                       print if /\b(?:$regex)\b/i;
720                       }
721
722       For more details on regular expression efficiency, see Mastering
723       Regular Expressions by Jeffrey Freidl.  He explains how regular
724       expressions engine work and why some patterns are surprisingly
725       inefficient.  Once you understand how perl applies regular expressions,
726       you can tune them for individual situations.
727
728   Why don't word-boundary searches with "\b" work for me?
729       (contributed by brian d foy)
730
731       Ensure that you know what \b really does: it's the boundary between a
732       word character, \w, and something that isn't a word character. That
733       thing that isn't a word character might be \W, but it can also be the
734       start or end of the string.
735
736       It's not (not!) the boundary between whitespace and non-whitespace, and
737       it's not the stuff between words we use to create sentences.
738
739       In regex speak, a word boundary (\b) is a "zero width assertion",
740       meaning that it doesn't represent a character in the string, but a
741       condition at a certain position.
742
743       For the regular expression, /\bPerl\b/, there has to be a word boundary
744       before the "P" and after the "l".  As long as something other than a
745       word character precedes the "P" and succeeds the "l", the pattern will
746       match. These strings match /\bPerl\b/.
747
748               "Perl"    # no word char before P or after l
749               "Perl "   # same as previous (space is not a word char)
750               "'Perl'"  # the ' char is not a word char
751               "Perl's"  # no word char before P, non-word char after "l"
752
753       These strings do not match /\bPerl\b/.
754
755               "Perl_"   # _ is a word char!
756               "Perler"  # no word char before P, but one after l
757
758       You don't have to use \b to match words though.  You can look for non-
759       word characters surrounded by word characters.  These strings match the
760       pattern /\b'\b/.
761
762               "don't"   # the ' char is surrounded by "n" and "t"
763               "qep'a'"  # the ' char is surrounded by "p" and "a"
764
765       These strings do not match /\b'\b/.
766
767               "foo'"    # there is no word char after non-word '
768
769       You can also use the complement of \b, \B, to specify that there should
770       not be a word boundary.
771
772       In the pattern /\Bam\B/, there must be a word character before the "a"
773       and after the "m". These patterns match /\Bam\B/:
774
775               "llama"   # "am" surrounded by word chars
776               "Samuel"  # same
777
778       These strings do not match /\Bam\B/
779
780               "Sam"      # no word boundary before "a", but one after "m"
781               "I am Sam" # "am" surrounded by non-word chars
782
783   Why does using $&, $`, or $' slow my program down?
784       (contributed by Anno Siegel)
785
786       Once Perl sees that you need one of these variables anywhere in the
787       program, it provides them on each and every pattern match. That means
788       that on every pattern match the entire string will be copied, part of
789       it to $`, part to $&, and part to $'. Thus the penalty is most severe
790       with long strings and patterns that match often. Avoid $&, $', and $`
791       if you can, but if you can't, once you've used them at all, use them at
792       will because you've already paid the price. Remember that some
793       algorithms really appreciate them. As of the 5.005 release, the $&
794       variable is no longer "expensive" the way the other two are.
795
796       Since Perl 5.6.1 the special variables @- and @+ can functionally
797       replace $`, $& and $'.  These arrays contain pointers to the beginning
798       and end of each match (see perlvar for the full story), so they give
799       you essentially the same information, but without the risk of excessive
800       string copying.
801
802       Perl 5.10 added three specials, "${^MATCH}", "${^PREMATCH}", and
803       "${^POSTMATCH}" to do the same job but without the global performance
804       penalty. Perl 5.10 only sets these variables if you compile or execute
805       the regular expression with the "/p" modifier.
806
807   What good is "\G" in a regular expression?
808       You use the "\G" anchor to start the next match on the same string
809       where the last match left off.  The regular expression engine cannot
810       skip over any characters to find the next match with this anchor, so
811       "\G" is similar to the beginning of string anchor, "^".  The "\G"
812       anchor is typically used with the "g" flag.  It uses the value of
813       "pos()" as the position to start the next match.  As the match operator
814       makes successive matches, it updates "pos()" with the position of the
815       next character past the last match (or the first character of the next
816       match, depending on how you like to look at it). Each string has its
817       own "pos()" value.
818
819       Suppose you want to match all of consecutive pairs of digits in a
820       string like "1122a44" and stop matching when you encounter non-digits.
821       You want to match 11 and 22 but the letter <a> shows up between 22 and
822       44 and you want to stop at "a". Simply matching pairs of digits skips
823       over the "a" and still matches 44.
824
825               $_ = "1122a44";
826               my @pairs = m/(\d\d)/g;   # qw( 11 22 44 )
827
828       If you use the "\G" anchor, you force the match after 22 to start with
829       the "a".  The regular expression cannot match there since it does not
830       find a digit, so the next match fails and the match operator returns
831       the pairs it already found.
832
833               $_ = "1122a44";
834               my @pairs = m/\G(\d\d)/g; # qw( 11 22 )
835
836       You can also use the "\G" anchor in scalar context. You still need the
837       "g" flag.
838
839               $_ = "1122a44";
840               while( m/\G(\d\d)/g )
841                       {
842                       print "Found $1\n";
843                       }
844
845       After the match fails at the letter "a", perl resets "pos()" and the
846       next match on the same string starts at the beginning.
847
848               $_ = "1122a44";
849               while( m/\G(\d\d)/g )
850                       {
851                       print "Found $1\n";
852                       }
853
854               print "Found $1 after while" if m/(\d\d)/g; # finds "11"
855
856       You can disable "pos()" resets on fail with the "c" flag, documented in
857       perlop and perlreref. Subsequent matches start where the last
858       successful match ended (the value of "pos()") even if a match on the
859       same string has failed in the meantime. In this case, the match after
860       the "while()" loop starts at the "a" (where the last match stopped),
861       and since it does not use any anchor it can skip over the "a" to find
862       44.
863
864               $_ = "1122a44";
865               while( m/\G(\d\d)/gc )
866                       {
867                       print "Found $1\n";
868                       }
869
870               print "Found $1 after while" if m/(\d\d)/g; # finds "44"
871
872       Typically you use the "\G" anchor with the "c" flag when you want to
873       try a different match if one fails, such as in a tokenizer. Jeffrey
874       Friedl offers this example which works in 5.004 or later.
875
876               while (<>) {
877                       chomp;
878                       PARSER: {
879                               m/ \G( \d+\b    )/gcx   && do { print "number: $1\n";  redo; };
880                               m/ \G( \w+      )/gcx   && do { print "word:   $1\n";  redo; };
881                               m/ \G( \s+      )/gcx   && do { print "space:  $1\n";  redo; };
882                               m/ \G( [^\w\d]+ )/gcx   && do { print "other:  $1\n";  redo; };
883                       }
884               }
885
886       For each line, the "PARSER" loop first tries to match a series of
887       digits followed by a word boundary.  This match has to start at the
888       place the last match left off (or the beginning of the string on the
889       first match). Since "m/ \G( \d+\b )/gcx" uses the "c" flag, if the
890       string does not match that regular expression, perl does not reset
891       pos() and the next match starts at the same position to try a different
892       pattern.
893
894   Are Perl regexes DFAs or NFAs?  Are they POSIX compliant?
895       While it's true that Perl's regular expressions resemble the DFAs
896       (deterministic finite automata) of the egrep(1) program, they are in
897       fact implemented as NFAs (non-deterministic finite automata) to allow
898       backtracking and backreferencing.  And they aren't POSIX-style either,
899       because those guarantee worst-case behavior for all cases.  (It seems
900       that some people prefer guarantees of consistency, even when what's
901       guaranteed is slowness.)  See the book "Mastering Regular Expressions"
902       (from O'Reilly) by Jeffrey Friedl for all the details you could ever
903       hope to know on these matters (a full citation appears in perlfaq2).
904
905   What's wrong with using grep in a void context?
906       The problem is that grep builds a return list, regardless of the
907       context.  This means you're making Perl go to the trouble of building a
908       list that you then just throw away. If the list is large, you waste
909       both time and space.  If your intent is to iterate over the list, then
910       use a for loop for this purpose.
911
912       In perls older than 5.8.1, map suffers from this problem as well.  But
913       since 5.8.1, this has been fixed, and map is context aware - in void
914       context, no lists are constructed.
915
916   How can I match strings with multibyte characters?
917       Starting from Perl 5.6 Perl has had some level of multibyte character
918       support.  Perl 5.8 or later is recommended.  Supported multibyte
919       character repertoires include Unicode, and legacy encodings through the
920       Encode module.  See perluniintro, perlunicode, and Encode.
921
922       If you are stuck with older Perls, you can do Unicode with the
923       "Unicode::String" module, and character conversions using the
924       "Unicode::Map8" and "Unicode::Map" modules.  If you are using Japanese
925       encodings, you might try using the jperl 5.005_03.
926
927       Finally, the following set of approaches was offered by Jeffrey Friedl,
928       whose article in issue #5 of The Perl Journal talks about this very
929       matter.
930
931       Let's suppose you have some weird Martian encoding where pairs of ASCII
932       uppercase letters encode single Martian letters (i.e. the two bytes
933       "CV" make a single Martian letter, as do the two bytes "SG", "VS",
934       "XX", etc.). Other bytes represent single characters, just like ASCII.
935
936       So, the string of Martian "I am CVSGXX!" uses 12 bytes to encode the
937       nine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.
938
939       Now, say you want to search for the single character "/GX/". Perl
940       doesn't know about Martian, so it'll find the two bytes "GX" in the "I
941       am CVSGXX!"  string, even though that character isn't there: it just
942       looks like it is because "SG" is next to "XX", but there's no real
943       "GX".  This is a big problem.
944
945       Here are a few ways, all painful, to deal with it:
946
947               # Make sure adjacent "martian" bytes are no longer adjacent.
948               $martian =~ s/([A-Z][A-Z])/ $1 /g;
949
950               print "found GX!\n" if $martian =~ /GX/;
951
952       Or like this:
953
954               @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;
955               # above is conceptually similar to:     @chars = $text =~ m/(.)/g;
956               #
957               foreach $char (@chars) {
958               print "found GX!\n", last if $char eq 'GX';
959               }
960
961       Or like this:
962
963               while ($martian =~ m/\G([A-Z][A-Z]|.)/gs) {  # \G probably unneeded
964                       print "found GX!\n", last if $1 eq 'GX';
965                       }
966
967       Here's another, slightly less painful, way to do it from Benjamin
968       Goldberg, who uses a zero-width negative look-behind assertion.
969
970               print "found GX!\n" if  $martian =~ m/
971                       (?<![A-Z])
972                       (?:[A-Z][A-Z])*?
973                       GX
974                       /x;
975
976       This succeeds if the "martian" character GX is in the string, and fails
977       otherwise.  If you don't like using (?<!), a zero-width negative look-
978       behind assertion, you can replace (?<![A-Z]) with (?:^|[^A-Z]).
979
980       It does have the drawback of putting the wrong thing in $-[0] and
981       $+[0], but this usually can be worked around.
982
983   How do I match a regular expression that's in a variable? ,
984       (contributed by brian d foy)
985
986       We don't have to hard-code patterns into the match operator (or
987       anything else that works with regular expressions). We can put the
988       pattern in a variable for later use.
989
990       The match operator is a double quote context, so you can interpolate
991       your variable just like a double quoted string. In this case, you read
992       the regular expression as user input and store it in $regex.  Once you
993       have the pattern in $regex, you use that variable in the match
994       operator.
995
996               chomp( my $regex = <STDIN> );
997
998               if( $string =~ m/$regex/ ) { ... }
999
1000       Any regular expression special characters in $regex are still special,
1001       and the pattern still has to be valid or Perl will complain.  For
1002       instance, in this pattern there is an unpaired parenthesis.
1003
1004               my $regex = "Unmatched ( paren";
1005
1006               "Two parens to bind them all" =~ m/$regex/;
1007
1008       When Perl compiles the regular expression, it treats the parenthesis as
1009       the start of a memory match. When it doesn't find the closing
1010       parenthesis, it complains:
1011
1012               Unmatched ( in regex; marked by <-- HERE in m/Unmatched ( <-- HERE  paren/ at script line 3.
1013
1014       You can get around this in several ways depending on our situation.
1015       First, if you don't want any of the characters in the string to be
1016       special, you can escape them with "quotemeta" before you use the
1017       string.
1018
1019               chomp( my $regex = <STDIN> );
1020               $regex = quotemeta( $regex );
1021
1022               if( $string =~ m/$regex/ ) { ... }
1023
1024       You can also do this directly in the match operator using the "\Q" and
1025       "\E" sequences. The "\Q" tells Perl where to start escaping special
1026       characters, and the "\E" tells it where to stop (see perlop for more
1027       details).
1028
1029               chomp( my $regex = <STDIN> );
1030
1031               if( $string =~ m/\Q$regex\E/ ) { ... }
1032
1033       Alternately, you can use "qr//", the regular expression quote operator
1034       (see perlop for more details).  It quotes and perhaps compiles the
1035       pattern, and you can apply regular expression flags to the pattern.
1036
1037               chomp( my $input = <STDIN> );
1038
1039               my $regex = qr/$input/is;
1040
1041               $string =~ m/$regex/  # same as m/$input/is;
1042
1043       You might also want to trap any errors by wrapping an "eval" block
1044       around the whole thing.
1045
1046               chomp( my $input = <STDIN> );
1047
1048               eval {
1049                       if( $string =~ m/\Q$input\E/ ) { ... }
1050                       };
1051               warn $@ if $@;
1052
1053       Or...
1054
1055               my $regex = eval { qr/$input/is };
1056               if( defined $regex ) {
1057                       $string =~ m/$regex/;
1058                       }
1059               else {
1060                       warn $@;
1061                       }
1062
1064       Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other
1065       authors as noted. All rights reserved.
1066
1067       This documentation is free; you can redistribute it and/or modify it
1068       under the same terms as Perl itself.
1069
1070       Irrespective of its distribution, all code examples in this file are
1071       hereby placed into the public domain.  You are permitted and encouraged
1072       to use this code in your own programs for fun or for profit as you see
1073       fit.  A simple comment in the code giving credit would be courteous but
1074       is not required.
1075
1076
1077
1078perl v5.12.4                      2011-06-07                       PERLFAQ6(1)
Impressum