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