3 perlfaq6 - Regular Expressions
7 This section is surprisingly small because the rest of the FAQ is
8 littered with answers involving regular expressions. For example,
9 decoding a URL and checking whether something is a number are handled
10 with regular expressions, but those answers are found elsewhere in
11 this document (in L<perlfaq9>: "How do I decode or create those %-encodings
12 on the web" and L<perlfaq4>: "How do I determine whether a scalar is
13 a number/whole/integer/float", to be precise).
15 =head2 How can I hope to use regular expressions without creating illegible and unmaintainable code?
16 X<regex, legibility> X<regexp, legibility>
17 X<regular expression, legibility> X</x>
19 Three techniques can make regular expressions maintainable and
24 =item Comments Outside the Regex
26 Describe what you're doing and how you're doing it, using normal Perl
29 # turn the line into the first word, a colon, and the
30 # number of characters on the rest of the line
31 s/^(\w+)(.*)/ lc($1) . ":" . length($2) /meg;
33 =item Comments Inside the Regex
35 The C</x> modifier causes whitespace to be ignored in a regex pattern
36 (except in a character class), and also allows you to use normal
37 comments there, too. As you can imagine, whitespace and comments help
40 C</x> lets you turn this:
42 s{<(?:[^>'"]*|".*?"|'.*?')+>}{}gs;
46 s{ < # opening angle bracket
47 (?: # Non-backreffing grouping paren
48 [^>'"] * # 0 or more things that are neither > nor ' nor "
50 ".*?" # a section between double quotes (stingy match)
52 '.*?' # a section between single quotes (stingy match)
53 ) + # all occurring one or more times
54 > # closing angle bracket
55 }{}gsx; # replace with nothing, i.e. delete
57 It's still not quite so clear as prose, but it is very useful for
58 describing the meaning of each part of the pattern.
60 =item Different Delimiters
62 While we normally think of patterns as being delimited with C</>
63 characters, they can be delimited by almost any character. L<perlre>
64 describes this. For example, the C<s///> above uses braces as
65 delimiters. Selecting another delimiter can avoid quoting the
66 delimiter within the pattern:
68 s/\/usr\/local/\/usr\/share/g; # bad delimiter choice
69 s#/usr/local#/usr/share#g; # better
73 =head2 I'm having trouble matching over more than one line. What's wrong?
74 X<regex, multiline> X<regexp, multiline> X<regular expression, multiline>
76 Either you don't have more than one line in the string you're looking
77 at (probably), or else you aren't using the correct modifier(s) on
78 your pattern (possibly).
80 There are many ways to get multiline data into a string. If you want
81 it to happen automatically while reading input, you'll want to set $/
82 (probably to '' for paragraphs or C<undef> for the whole file) to
83 allow you to read more than one line at a time.
85 Read L<perlre> to help you decide which of C</s> and C</m> (or both)
86 you might want to use: C</s> allows dot to include newline, and C</m>
87 allows caret and dollar to match next to a newline, not just at the
88 end of the string. You do need to make sure that you've actually
89 got a multiline string in there.
91 For example, this program detects duplicate words, even when they span
92 line breaks (but not paragraph ones). For this example, we don't need
93 C</s> because we aren't using dot in a regular expression that we want
94 to cross line boundaries. Neither do we need C</m> because we aren't
95 wanting caret or dollar to match at any point inside the record next
96 to newlines. But it's imperative that $/ be set to something other
97 than the default, or else we won't actually ever have a multiline
100 $/ = ''; # read in whole paragraph, not just one line
102 while ( /\b([\w'-]+)(\s+\1)+\b/gi ) { # word starts alpha
103 print "Duplicate $1 at paragraph $.\n";
107 Here's code that finds sentences that begin with "From " (which would
108 be mangled by many mailers):
110 $/ = ''; # read in whole paragraph, not just one line
112 while ( /^From /gm ) { # /m makes ^ match next to \n
113 print "leading from in paragraph $.\n";
117 Here's code that finds everything between START and END in a paragraph:
119 undef $/; # read in whole file, not just one line or paragraph
121 while ( /START(.*?)END/sgm ) { # /s makes . cross line boundaries
126 =head2 How can I pull out lines between two patterns that are themselves on different lines?
129 You can use Perl's somewhat exotic C<..> operator (documented in
132 perl -ne 'print if /START/ .. /END/' file1 file2 ...
134 If you wanted text and not lines, you would use
136 perl -0777 -ne 'print "$1\n" while /START(.*?)END/gs' file1 file2 ...
138 But if you want nested occurrences of C<START> through C<END>, you'll
139 run up against the problem described in the question in this section
140 on matching balanced text.
142 Here's another example of using C<..>:
145 $in_header = 1 .. /^$/;
146 $in_body = /^$/ .. eof;
147 # now choose between them
149 $. = 0 if eof; # fix $.
152 =head2 How do I match XML, HTML, or other nasty, ugly things with a regex?
153 X<regex, XML> X<regex, HTML> X<XML> X<HTML> X<pain> X<frustration>
154 X<sucking out, will to live>
156 (contributed by brian d foy)
158 If you just want to get work done, use a module and forget about the
159 regular expressions. The C<XML::Parser> and C<HTML::Parser> modules
160 are good starts, although each namespace has other parsing modules
161 specialized for certain tasks and different ways of doing it. Start at
162 CPAN Search ( http://search.cpan.org ) and wonder at all the work people
163 have done for you already! :)
165 The problem with things such as XML is that they have balanced text
166 containing multiple levels of balanced text, but sometimes it isn't
167 balanced text, as in an empty tag (C<< <br/> >>, for instance). Even then,
168 things can occur out-of-order. Just when you think you've got a
169 pattern that matches your input, someone throws you a curveball.
171 If you'd like to do it the hard way, scratching and clawing your way
172 toward a right answer but constantly being disappointed, besieged by
173 bug reports, and weary from the inordinate amount of time you have to
174 spend reinventing a triangular wheel, then there are several things
175 you can try before you give up in frustration:
179 =item * Solve the balanced text problem from another question in L<perlfaq6>
181 =item * Try the recursive regex features in Perl 5.10 and later. See L<perlre>
183 =item * Try defining a grammar using Perl 5.10's C<(?DEFINE)> feature.
185 =item * Break the problem down into sub-problems instead of trying to use a single regex
187 =item * Convince everyone not to use XML or HTML in the first place
193 =head2 I put a regular expression into $/ but it didn't work. What's wrong?
194 X<$/, regexes in> X<$INPUT_RECORD_SEPARATOR, regexes in>
197 $/ has to be a string. You can use these examples if you really need to
200 If you have File::Stream, this is easy.
204 my $stream = File::Stream->new(
206 separator => qr/\s*,\s*/,
209 print "$_\n" while <$stream>;
211 If you don't have File::Stream, you have to do a little more work.
213 You can use the four-argument form of sysread to continually add to
214 a buffer. After you add to the buffer, you check if you have a
215 complete line (using your regular expression).
218 while( sysread FH, $_, 8192, length ) {
219 while( s/^((?s).*?)your_pattern// ) {
225 You can do the same thing with foreach and a match using the
226 c flag and the \G anchor, if you do not mind your entire file
227 being in memory at the end.
230 while( sysread FH, $_, 8192, length ) {
231 foreach my $record ( m/\G((?s).*?)your_pattern/gc ) {
234 substr( $_, 0, pos ) = "" if pos;
238 =head2 How do I substitute case insensitively on the LHS while preserving case on the RHS?
239 X<replace, case preserving> X<substitute, case preserving>
240 X<substitution, case preserving> X<s, case preserving>
242 Here's a lovely Perlish solution by Larry Rosler. It exploits
243 properties of bitwise xor on ASCII strings.
245 $_= "this is a TEsT case";
251 { uc $new | (uc $1 ^ $1) .
252 (uc(substr $1, -1) ^ substr $1, -1) x
253 (length($new) - length $1)
258 And here it is as a subroutine, modeled after the above:
260 sub preserve_case($$) {
261 my ($old, $new) = @_;
262 my $mask = uc $old ^ $old;
265 substr($mask, -1) x (length($new) - length($old))
268 $string = "this is a TEsT case";
269 $string =~ s/(test)/preserve_case($1, "success")/egi;
274 this is a SUcCESS case
276 As an alternative, to keep the case of the replacement word if it is
277 longer than the original, you can use this code, by Jeff Pinyan:
280 my ($from, $to) = @_;
281 my ($lf, $lt) = map length, @_;
283 if ($lt < $lf) { $from = substr $from, 0, $lt }
284 else { $from .= substr $to, $lf }
286 return uc $to | ($from ^ uc $from);
289 This changes the sentence to "this is a SUcCess case."
291 Just to show that C programmers can write C in any programming language,
292 if you prefer a more C-like solution, the following script makes the
293 substitution have the same case, letter by letter, as the original.
294 (It also happens to run about 240% slower than the Perlish solution runs.)
295 If the substitution has more characters than the string being substituted,
296 the case of the last character is used for the rest of the substitution.
298 # Original by Nathan Torkington, massaged by Jeffrey Friedl
300 sub preserve_case($$)
302 my ($old, $new) = @_;
303 my ($state) = 0; # 0 = no change; 1 = lc; 2 = uc
304 my ($i, $oldlen, $newlen, $c) = (0, length($old), length($new));
305 my ($len) = $oldlen < $newlen ? $oldlen : $newlen;
307 for ($i = 0; $i < $len; $i++) {
308 if ($c = substr($old, $i, 1), $c =~ /[\W\d_]/) {
310 } elsif (lc $c eq $c) {
311 substr($new, $i, 1) = lc(substr($new, $i, 1));
314 substr($new, $i, 1) = uc(substr($new, $i, 1));
318 # finish up with any remaining new (for when new is longer than old)
319 if ($newlen > $oldlen) {
321 substr($new, $oldlen) = lc(substr($new, $oldlen));
322 } elsif ($state == 2) {
323 substr($new, $oldlen) = uc(substr($new, $oldlen));
329 =head2 How can I make C<\w> match national character sets?
332 Put C<use locale;> in your script. The \w character class is taken
333 from the current locale.
335 See L<perllocale> for details.
337 =head2 How can I match a locale-smart version of C</[a-zA-Z]/>?
340 You can use the POSIX character class syntax C</[[:alpha:]]/>
341 documented in L<perlre>.
343 No matter which locale you are in, the alphabetic characters are
344 the characters in \w without the digits and the underscore.
345 As a regex, that looks like C</[^\W\d_]/>. Its complement,
346 the non-alphabetics, is then everything in \W along with
347 the digits and the underscore, or C</[\W\d_]/>.
349 =head2 How can I quote a variable to use in a regex?
350 X<regex, escaping> X<regexp, escaping> X<regular expression, escaping>
352 The Perl parser will expand $variable and @variable references in
353 regular expressions unless the delimiter is a single quote. Remember,
354 too, that the right-hand side of a C<s///> substitution is considered
355 a double-quoted string (see L<perlop> for more details). Remember
356 also that any regex special characters will be acted on unless you
357 precede the substitution with \Q. Here's an example:
359 $string = "Placido P. Octopus";
362 $string =~ s/$regex/Polyp/;
363 # $string is now "Polypacido P. Octopus"
365 Because C<.> is special in regular expressions, and can match any
366 single character, the regex C<P.> here has matched the <Pl> in the
369 To escape the special meaning of C<.>, we use C<\Q>:
371 $string = "Placido P. Octopus";
374 $string =~ s/\Q$regex/Polyp/;
375 # $string is now "Placido Polyp Octopus"
377 The use of C<\Q> causes the <.> in the regex to be treated as a
378 regular character, so that C<P.> matches a C<P> followed by a dot.
380 =head2 What is C</o> really for?
381 X</o, regular expressions> X<compile, regular expressions>
383 (contributed by brian d foy)
385 The C</o> option for regular expressions (documented in L<perlop> and
386 L<perlreref>) tells Perl to compile the regular expression only once.
387 This is only useful when the pattern contains a variable. Perls 5.6
388 and later handle this automatically if the pattern does not change.
390 Since the match operator C<m//>, the substitution operator C<s///>,
391 and the regular expression quoting operator C<qr//> are double-quotish
392 constructs, you can interpolate variables into the pattern. See the
393 answer to "How can I quote a variable to use in a regex?" for more
396 This example takes a regular expression from the argument list and
397 prints the lines of input that match it:
399 my $pattern = shift @ARGV;
402 print if m/$pattern/;
405 Versions of Perl prior to 5.6 would recompile the regular expression
406 for each iteration, even if C<$pattern> had not changed. The C</o>
407 would prevent this by telling Perl to compile the pattern the first
408 time, then reuse that for subsequent iterations:
410 my $pattern = shift @ARGV;
413 print if m/$pattern/o; # useful for Perl < 5.6
416 In versions 5.6 and later, Perl won't recompile the regular expression
417 if the variable hasn't changed, so you probably don't need the C</o>
418 option. It doesn't hurt, but it doesn't help either. If you want any
419 version of Perl to compile the regular expression only once even if
420 the variable changes (thus, only using its initial value), you still
423 You can watch Perl's regular expression engine at work to verify for
424 yourself if Perl is recompiling a regular expression. The C<use re
425 'debug'> pragma (comes with Perl 5.005 and later) shows the details.
426 With Perls before 5.6, you should see C<re> reporting that its
427 compiling the regular expression on each iteration. With Perl 5.6 or
428 later, you should only see C<re> report that for the first iteration.
433 foreach ( qw(Perl Java Ruby Python) ) {
434 print STDERR "-" x 73, "\n";
435 print STDERR "Trying $_...\n";
436 print STDERR "\t$_ is good!\n" if m/$regex/;
439 =head2 How do I use a regular expression to strip C style comments from a file?
441 While this actually can be done, it's much harder than you'd think.
442 For example, this one-liner
444 perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c
446 will work in many but not all cases. You see, it's too simple-minded for
447 certain kinds of C programs, in particular, those with what appear to be
448 comments in quoted strings. For that, you'd need something like this,
449 created by Jeffrey Friedl and later modified by Fred Curtis.
453 s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $2 ? $2 : ""#gse;
456 This could, of course, be more legibly written with the C</x> modifier, adding
457 whitespace and comments. Here it is expanded, courtesy of Fred Curtis.
460 /\* ## Start of /* ... */ comment
461 [^*]*\*+ ## Non-* followed by 1-or-more *'s
464 )* ## 0-or-more things which don't start with /
465 ## but do end with '*'
466 / ## End of /* ... */ comment
468 | ## OR various things which aren't comments:
471 " ## Start of " ... " string
477 " ## End of " ... " string
481 ' ## Start of ' ... ' string
487 ' ## End of ' ... ' string
491 . ## Anything other char
492 [^/"'\\]* ## Chars which doesn't start a comment, string or escape
494 }{defined $2 ? $2 : ""}gxse;
496 A slight modification also removes C++ comments, possibly spanning multiple lines
497 using a continuation character:
499 s#/\*[^*]*\*+([^/*][^*]*\*+)*/|//([^\\]|[^\n][\n]?)*?\n|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $3 ? $3 : ""#gse;
501 =head2 Can I use Perl regular expressions to match balanced text?
502 X<regex, matching balanced test> X<regexp, matching balanced test>
503 X<regular expression, matching balanced test> X<possessive> X<PARNO>
504 X<Text::Balanced> X<Regexp::Common> X<backtracking> X<recursion>
506 (contributed by brian d foy)
508 Your first try should probably be the C<Text::Balanced> module, which
509 is in the Perl standard library since Perl 5.8. It has a variety of
510 functions to deal with tricky text. The C<Regexp::Common> module can
511 also help by providing canned patterns you can use.
513 As of Perl 5.10, you can match balanced text with regular expressions
514 using recursive patterns. Before Perl 5.10, you had to resort to
515 various tricks such as using Perl code in C<(??{})> sequences.
517 Here's an example using a recursive regular expression. The goal is to
518 capture all of the text within angle brackets, including the text in
519 nested angle brackets. This sample text has two "major" groups: a
520 group with one level of nesting and a group with two levels of
521 nesting. There are five total groups in angle brackets:
523 I have some <brackets in <nested brackets> > and
524 <another group <nested once <nested twice> > >
527 The regular expression to match the balanced text uses two new (to
528 Perl 5.10) regular expression features. These are covered in L<perlre>
529 and this example is a modified version of one in that documentation.
531 First, adding the new possessive C<+> to any quantifier finds the
532 longest match and does not backtrack. That's important since you want
533 to handle any angle brackets through the recursion, not backtracking.
534 The group C<< [^<>]++ >> finds one or more non-angle brackets without
537 Second, the new C<(?PARNO)> refers to the sub-pattern in the
538 particular capture buffer given by C<PARNO>. In the following regex,
539 the first capture buffer finds (and remembers) the balanced text, and
540 you need that same pattern within the first buffer to get past the
541 nested text. That's the recursive part. The C<(?1)> uses the pattern
542 in the outer capture buffer as an independent part of the regex.
544 Putting it all together, you have:
546 #!/usr/local/bin/perl5.10.0
548 my $string =<<"HERE";
549 I have some <brackets in <nested brackets> > and
550 <another group <nested once <nested twice> > >
554 my @groups = $string =~ m/
555 ( # start of capture buffer 1
556 < # match an opening angle bracket
558 [^<>]++ # one or more non angle brackets, non backtracking
560 (?1) # found < or >, so recurse to capture buffer 1
562 > # match a closing angle bracket
563 ) # end of capture buffer 1
567 print "Found:\n\t@groups\n";
569 The output shows that Perl found the two major groups:
572 <brackets in <nested brackets> >
573 <another group <nested once <nested twice> > >
575 With a little extra work, you can get the all of the groups in angle
576 brackets even if they are in other angle brackets too. Each time you
577 get a balanced match, remove its outer delimiter (that's the one you
578 just matched so don't match it again) and add it to a queue of strings
579 to process. Keep doing that until you get no matches:
581 #!/usr/local/bin/perl5.10.0
584 I have some <brackets in <nested brackets> > and
585 <another group <nested once <nested twice> > >
590 ( # start of bracket 1
591 < # match an opening angle bracket
593 [^<>]++ # one or more non angle brackets, non backtracking
595 (?1) # recurse to bracket 1
597 > # match a closing angle bracket
605 my $string = shift @queue;
607 my @groups = $string =~ m/$regex/g;
608 print "Found:\n\t@groups\n\n" if @groups;
610 unshift @queue, map { s/^<//; s/>$//; $_ } @groups;
613 The output shows all of the groups. The outermost matches show up
614 first and the nested matches so up later:
617 <brackets in <nested brackets> >
618 <another group <nested once <nested twice> > >
624 <nested once <nested twice> >
629 =head2 What does it mean that regexes are greedy? How can I get around it?
630 X<greedy> X<greediness>
632 Most people mean that greedy regexes match as much as they can.
633 Technically speaking, it's actually the quantifiers (C<?>, C<*>, C<+>,
634 C<{}>) that are greedy rather than the whole pattern; Perl prefers local
635 greed and immediate gratification to overall greed. To get non-greedy
636 versions of the same quantifiers, use (C<??>, C<*?>, C<+?>, C<{}?>).
640 $s1 = $s2 = "I am very very cold";
641 $s1 =~ s/ve.*y //; # I am cold
642 $s2 =~ s/ve.*?y //; # I am very cold
644 Notice how the second substitution stopped matching as soon as it
645 encountered "y ". The C<*?> quantifier effectively tells the regular
646 expression engine to find a match as quickly as possible and pass
647 control on to whatever is next in line, like you would if you were
650 =head2 How do I process each word on each line?
653 Use the split function:
656 foreach $word ( split ) {
657 # do something with $word here
661 Note that this isn't really a word in the English sense; it's just
662 chunks of consecutive non-whitespace characters.
664 To work with only alphanumeric sequences (including underscores), you
668 foreach $word (m/(\w+)/g) {
669 # do something with $word here
673 =head2 How can I print out a word-frequency or line-frequency summary?
675 To do this, you have to parse out each word in the input stream. We'll
676 pretend that by word you mean chunk of alphabetics, hyphens, or
677 apostrophes, rather than the non-whitespace chunk idea of a word given
678 in the previous question:
681 while ( /(\b[^\W_\d][\w'-]+\b)/g ) { # misses "`sheep'"
686 while ( ($word, $count) = each %seen ) {
687 print "$count $word\n";
690 If you wanted to do the same thing for lines, you wouldn't need a
697 while ( ($line, $count) = each %seen ) {
698 print "$count $line";
701 If you want these output in a sorted order, see L<perlfaq4>: "How do I
702 sort a hash (optionally by value instead of key)?".
704 =head2 How can I do approximate matching?
705 X<match, approximate> X<matching, approximate>
707 See the module String::Approx available from CPAN.
709 =head2 How do I efficiently match many regular expressions at once?
710 X<regex, efficiency> X<regexp, efficiency>
711 X<regular expression, efficiency>
713 ( contributed by brian d foy )
715 Avoid asking Perl to compile a regular expression every time
716 you want to match it. In this example, perl must recompile
717 the regular expression for every iteration of the C<foreach>
718 loop since it has no way to know what $pattern will be.
720 @patterns = qw( foo bar baz );
722 LINE: while( <DATA> )
724 foreach $pattern ( @patterns )
726 if( /\b$pattern\b/i )
734 The C<qr//> operator showed up in perl 5.005. It compiles a
735 regular expression, but doesn't apply it. When you use the
736 pre-compiled version of the regex, perl does less work. In
737 this example, I inserted a C<map> to turn each pattern into
738 its pre-compiled form. The rest of the script is the same,
741 @patterns = map { qr/\b$_\b/i } qw( foo bar baz );
745 foreach $pattern ( @patterns )
755 In some cases, you may be able to make several patterns into
756 a single regular expression. Beware of situations that require
759 $regex = join '|', qw( foo bar baz );
763 print if /\b(?:$regex)\b/i;
766 For more details on regular expression efficiency, see I<Mastering
767 Regular Expressions> by Jeffrey Freidl. He explains how regular
768 expressions engine work and why some patterns are surprisingly
769 inefficient. Once you understand how perl applies regular
770 expressions, you can tune them for individual situations.
772 =head2 Why don't word-boundary searches with C<\b> work for me?
775 (contributed by brian d foy)
777 Ensure that you know what \b really does: it's the boundary between a
778 word character, \w, and something that isn't a word character. That
779 thing that isn't a word character might be \W, but it can also be the
780 start or end of the string.
782 It's not (not!) the boundary between whitespace and non-whitespace,
783 and it's not the stuff between words we use to create sentences.
785 In regex speak, a word boundary (\b) is a "zero width assertion",
786 meaning that it doesn't represent a character in the string, but a
787 condition at a certain position.
789 For the regular expression, /\bPerl\b/, there has to be a word
790 boundary before the "P" and after the "l". As long as something other
791 than a word character precedes the "P" and succeeds the "l", the
792 pattern will match. These strings match /\bPerl\b/.
794 "Perl" # no word char before P or after l
795 "Perl " # same as previous (space is not a word char)
796 "'Perl'" # the ' char is not a word char
797 "Perl's" # no word char before P, non-word char after "l"
799 These strings do not match /\bPerl\b/.
801 "Perl_" # _ is a word char!
802 "Perler" # no word char before P, but one after l
804 You don't have to use \b to match words though. You can look for
805 non-word characters surrounded by word characters. These strings
806 match the pattern /\b'\b/.
808 "don't" # the ' char is surrounded by "n" and "t"
809 "qep'a'" # the ' char is surrounded by "p" and "a"
811 These strings do not match /\b'\b/.
813 "foo'" # there is no word char after non-word '
815 You can also use the complement of \b, \B, to specify that there
816 should not be a word boundary.
818 In the pattern /\Bam\B/, there must be a word character before the "a"
819 and after the "m". These patterns match /\Bam\B/:
821 "llama" # "am" surrounded by word chars
824 These strings do not match /\Bam\B/
826 "Sam" # no word boundary before "a", but one after "m"
827 "I am Sam" # "am" surrounded by non-word chars
830 =head2 Why does using $&, $`, or $' slow my program down?
831 X<$MATCH> X<$&> X<$POSTMATCH> X<$'> X<$PREMATCH> X<$`>
833 (contributed by Anno Siegel)
835 Once Perl sees that you need one of these variables anywhere in the
836 program, it provides them on each and every pattern match. That means
837 that on every pattern match the entire string will be copied, part of it
838 to $`, part to $&, and part to $'. Thus the penalty is most severe with
839 long strings and patterns that match often. Avoid $&, $', and $` if you
840 can, but if you can't, once you've used them at all, use them at will
841 because you've already paid the price. Remember that some algorithms
842 really appreciate them. As of the 5.005 release, the $& variable is no
843 longer "expensive" the way the other two are.
845 Since Perl 5.6.1 the special variables @- and @+ can functionally replace
846 $`, $& and $'. These arrays contain pointers to the beginning and end
847 of each match (see perlvar for the full story), so they give you
848 essentially the same information, but without the risk of excessive
851 Perl 5.10 added three specials, C<${^MATCH}>, C<${^PREMATCH}>, and
852 C<${^POSTMATCH}> to do the same job but without the global performance
853 penalty. Perl 5.10 only sets these variables if you compile or execute the
854 regular expression with the C</p> modifier.
856 =head2 What good is C<\G> in a regular expression?
859 You use the C<\G> anchor to start the next match on the same
860 string where the last match left off. The regular
861 expression engine cannot skip over any characters to find
862 the next match with this anchor, so C<\G> is similar to the
863 beginning of string anchor, C<^>. The C<\G> anchor is typically
864 used with the C<g> flag. It uses the value of C<pos()>
865 as the position to start the next match. As the match
866 operator makes successive matches, it updates C<pos()> with the
867 position of the next character past the last match (or the
868 first character of the next match, depending on how you like
869 to look at it). Each string has its own C<pos()> value.
871 Suppose you want to match all of consecutive pairs of digits
872 in a string like "1122a44" and stop matching when you
873 encounter non-digits. You want to match C<11> and C<22> but
874 the letter <a> shows up between C<22> and C<44> and you want
875 to stop at C<a>. Simply matching pairs of digits skips over
876 the C<a> and still matches C<44>.
879 my @pairs = m/(\d\d)/g; # qw( 11 22 44 )
881 If you use the C<\G> anchor, you force the match after C<22> to
882 start with the C<a>. The regular expression cannot match
883 there since it does not find a digit, so the next match
884 fails and the match operator returns the pairs it already
888 my @pairs = m/\G(\d\d)/g; # qw( 11 22 )
890 You can also use the C<\G> anchor in scalar context. You
891 still need the C<g> flag.
894 while( m/\G(\d\d)/g )
899 After the match fails at the letter C<a>, perl resets C<pos()>
900 and the next match on the same string starts at the beginning.
903 while( m/\G(\d\d)/g )
908 print "Found $1 after while" if m/(\d\d)/g; # finds "11"
910 You can disable C<pos()> resets on fail with the C<c> flag, documented
911 in L<perlop> and L<perlreref>. Subsequent matches start where the last
912 successful match ended (the value of C<pos()>) even if a match on the
913 same string has failed in the meantime. In this case, the match after
914 the C<while()> loop starts at the C<a> (where the last match stopped),
915 and since it does not use any anchor it can skip over the C<a> to find
919 while( m/\G(\d\d)/gc )
924 print "Found $1 after while" if m/(\d\d)/g; # finds "44"
926 Typically you use the C<\G> anchor with the C<c> flag
927 when you want to try a different match if one fails,
928 such as in a tokenizer. Jeffrey Friedl offers this example
929 which works in 5.004 or later.
934 m/ \G( \d+\b )/gcx && do { print "number: $1\n"; redo; };
935 m/ \G( \w+ )/gcx && do { print "word: $1\n"; redo; };
936 m/ \G( \s+ )/gcx && do { print "space: $1\n"; redo; };
937 m/ \G( [^\w\d]+ )/gcx && do { print "other: $1\n"; redo; };
941 For each line, the C<PARSER> loop first tries to match a series
942 of digits followed by a word boundary. This match has to
943 start at the place the last match left off (or the beginning
944 of the string on the first match). Since C<m/ \G( \d+\b
945 )/gcx> uses the C<c> flag, if the string does not match that
946 regular expression, perl does not reset pos() and the next
947 match starts at the same position to try a different
950 =head2 Are Perl regexes DFAs or NFAs? Are they POSIX compliant?
951 X<DFA> X<NFA> X<POSIX>
953 While it's true that Perl's regular expressions resemble the DFAs
954 (deterministic finite automata) of the egrep(1) program, they are in
955 fact implemented as NFAs (non-deterministic finite automata) to allow
956 backtracking and backreferencing. And they aren't POSIX-style either,
957 because those guarantee worst-case behavior for all cases. (It seems
958 that some people prefer guarantees of consistency, even when what's
959 guaranteed is slowness.) See the book "Mastering Regular Expressions"
960 (from O'Reilly) by Jeffrey Friedl for all the details you could ever
961 hope to know on these matters (a full citation appears in
964 =head2 What's wrong with using grep in a void context?
967 The problem is that grep builds a return list, regardless of the context.
968 This means you're making Perl go to the trouble of building a list that
969 you then just throw away. If the list is large, you waste both time and space.
970 If your intent is to iterate over the list, then use a for loop for this
973 In perls older than 5.8.1, map suffers from this problem as well.
974 But since 5.8.1, this has been fixed, and map is context aware - in void
975 context, no lists are constructed.
977 =head2 How can I match strings with multibyte characters?
978 X<regex, and multibyte characters> X<regexp, and multibyte characters>
979 X<regular expression, and multibyte characters> X<martian> X<encoding, Martian>
981 Starting from Perl 5.6 Perl has had some level of multibyte character
982 support. Perl 5.8 or later is recommended. Supported multibyte
983 character repertoires include Unicode, and legacy encodings
984 through the Encode module. See L<perluniintro>, L<perlunicode>,
987 If you are stuck with older Perls, you can do Unicode with the
988 C<Unicode::String> module, and character conversions using the
989 C<Unicode::Map8> and C<Unicode::Map> modules. If you are using
990 Japanese encodings, you might try using the jperl 5.005_03.
992 Finally, the following set of approaches was offered by Jeffrey
993 Friedl, whose article in issue #5 of The Perl Journal talks about
996 Let's suppose you have some weird Martian encoding where pairs of
997 ASCII uppercase letters encode single Martian letters (i.e. the two
998 bytes "CV" make a single Martian letter, as do the two bytes "SG",
999 "VS", "XX", etc.). Other bytes represent single characters, just like
1002 So, the string of Martian "I am CVSGXX!" uses 12 bytes to encode the
1003 nine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.
1005 Now, say you want to search for the single character C</GX/>. Perl
1006 doesn't know about Martian, so it'll find the two bytes "GX" in the "I
1007 am CVSGXX!" string, even though that character isn't there: it just
1008 looks like it is because "SG" is next to "XX", but there's no real
1009 "GX". This is a big problem.
1011 Here are a few ways, all painful, to deal with it:
1013 # Make sure adjacent "martian" bytes are no longer adjacent.
1014 $martian =~ s/([A-Z][A-Z])/ $1 /g;
1016 print "found GX!\n" if $martian =~ /GX/;
1020 @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;
1021 # above is conceptually similar to: @chars = $text =~ m/(.)/g;
1023 foreach $char (@chars) {
1024 print "found GX!\n", last if $char eq 'GX';
1029 while ($martian =~ m/\G([A-Z][A-Z]|.)/gs) { # \G probably unneeded
1030 print "found GX!\n", last if $1 eq 'GX';
1033 Here's another, slightly less painful, way to do it from Benjamin
1034 Goldberg, who uses a zero-width negative look-behind assertion.
1036 print "found GX!\n" if $martian =~ m/
1042 This succeeds if the "martian" character GX is in the string, and fails
1043 otherwise. If you don't like using (?<!), a zero-width negative
1044 look-behind assertion, you can replace (?<![A-Z]) with (?:^|[^A-Z]).
1046 It does have the drawback of putting the wrong thing in $-[0] and $+[0],
1047 but this usually can be worked around.
1049 =head2 How do I match a regular expression that's in a variable?
1050 X<regex, in variable> X<eval> X<regex> X<quotemeta> X<\Q, regex>
1051 X<\E, regex>, X<qr//>
1053 (contributed by brian d foy)
1055 We don't have to hard-code patterns into the match operator (or
1056 anything else that works with regular expressions). We can put the
1057 pattern in a variable for later use.
1059 The match operator is a double quote context, so you can interpolate
1060 your variable just like a double quoted string. In this case, you
1061 read the regular expression as user input and store it in C<$regex>.
1062 Once you have the pattern in C<$regex>, you use that variable in the
1065 chomp( my $regex = <STDIN> );
1067 if( $string =~ m/$regex/ ) { ... }
1069 Any regular expression special characters in C<$regex> are still
1070 special, and the pattern still has to be valid or Perl will complain.
1071 For instance, in this pattern there is an unpaired parenthesis.
1073 my $regex = "Unmatched ( paren";
1075 "Two parens to bind them all" =~ m/$regex/;
1077 When Perl compiles the regular expression, it treats the parenthesis
1078 as the start of a memory match. When it doesn't find the closing
1079 parenthesis, it complains:
1081 Unmatched ( in regex; marked by <-- HERE in m/Unmatched ( <-- HERE paren/ at script line 3.
1083 You can get around this in several ways depending on our situation.
1084 First, if you don't want any of the characters in the string to be
1085 special, you can escape them with C<quotemeta> before you use the string.
1087 chomp( my $regex = <STDIN> );
1088 $regex = quotemeta( $regex );
1090 if( $string =~ m/$regex/ ) { ... }
1092 You can also do this directly in the match operator using the C<\Q>
1093 and C<\E> sequences. The C<\Q> tells Perl where to start escaping
1094 special characters, and the C<\E> tells it where to stop (see L<perlop>
1097 chomp( my $regex = <STDIN> );
1099 if( $string =~ m/\Q$regex\E/ ) { ... }
1101 Alternately, you can use C<qr//>, the regular expression quote operator (see
1102 L<perlop> for more details). It quotes and perhaps compiles the pattern,
1103 and you can apply regular expression flags to the pattern.
1105 chomp( my $input = <STDIN> );
1107 my $regex = qr/$input/is;
1109 $string =~ m/$regex/ # same as m/$input/is;
1111 You might also want to trap any errors by wrapping an C<eval> block
1112 around the whole thing.
1114 chomp( my $input = <STDIN> );
1117 if( $string =~ m/\Q$input\E/ ) { ... }
1123 my $regex = eval { qr/$input/is };
1124 if( defined $regex ) {
1125 $string =~ m/$regex/;
1131 =head1 AUTHOR AND COPYRIGHT
1133 Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and
1134 other authors as noted. All rights reserved.
1136 This documentation is free; you can redistribute it and/or modify it
1137 under the same terms as Perl itself.
1139 Irrespective of its distribution, all code examples in this file
1140 are hereby placed into the public domain. You are permitted and
1141 encouraged to use this code in your own programs for fun
1142 or for profit as you see fit. A simple comment in the code giving
1143 credit would be courteous but is not required.