Two doublewords less
[p5sagit/p5-mst-13.2.git] / pod / perlfaq6.pod
CommitLineData
68dc0745 1=head1 NAME
2
3fe9a6f1 3perlfaq6 - Regexps ($Revision: 1.16 $, $Date: 1997/03/25 18:16:56 $)
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
11this document (in the section on Data and the Networking one on
12networking, to be precise).
13
54310121 14=head2 How can I hope to use regular expressions without creating illegible and unmaintainable code?
68dc0745 15
16Three techniques can make regular expressions maintainable and
17understandable.
18
19=over 4
20
21=item Comments Outside the Regexp
22
23Describe what you're doing and how you're doing it, using normal Perl
24comments.
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) /ge;
29
30=item Comments Inside the Regexp
31
32The C</x> modifier causes whitespace to be ignored in a regexp pattern
33(except in a character class), and also allows you to use normal
34comments there, too. As you can imagine, whitespace and comments help
35a lot.
36
37C</x> lets you turn this:
38
39 s{<(?:[^>'"]*|".*?"|'.*?')+>}{}gs;
40
41into this:
42
43 s{ < # opening angle bracket
44 (?: # Non-backreffing grouping paren
45 [^>'"] * # 0 or more things that are neither > nor ' nor "
46 | # or else
47 ".*?" # a section between double quotes (stingy match)
48 | # or else
49 '.*?' # a section between single quotes (stingy match)
50 ) + # all occurring one or more times
51 > # closing angle bracket
52 }{}gsx; # replace with nothing, i.e. delete
53
54It's still not quite so clear as prose, but it is very useful for
55describing the meaning of each part of the pattern.
56
57=item Different Delimiters
58
59While we normally think of patterns as being delimited with C</>
60characters, they can be delimited by almost any character. L<perlre>
61describes this. For example, the C<s///> above uses braces as
62delimiters. Selecting another delimiter can avoid quoting the
63delimiter within the pattern:
64
65 s/\/usr\/local/\/usr\/share/g; # bad delimiter choice
66 s#/usr/local#/usr/share#g; # better
67
68=back
69
70=head2 I'm having trouble matching over more than one line. What's wrong?
71
72Either you don't have newlines in your string, or you aren't using the
73correct modifier(s) on your pattern.
74
75There are many ways to get multiline data into a string. If you want
76it to happen automatically while reading input, you'll want to set $/
77(probably to '' for paragraphs or C<undef> for the whole file) to
78allow you to read more than one line at a time.
79
80Read L<perlre> to help you decide which of C</s> and C</m> (or both)
81you might want to use: C</s> allows dot to include newline, and C</m>
82allows caret and dollar to match next to a newline, not just at the
83end of the string. You do need to make sure that you've actually
84got a multiline string in there.
85
86For example, this program detects duplicate words, even when they span
87line breaks (but not paragraph ones). For this example, we don't need
88C</s> because we aren't using dot in a regular expression that we want
89to cross line boundaries. Neither do we need C</m> because we aren't
90wanting caret or dollar to match at any point inside the record next
91to newlines. But it's imperative that $/ be set to something other
92than the default, or else we won't actually ever have a multiline
93record read in.
94
95 $/ = ''; # read in more whole paragraph, not just one line
96 while ( <> ) {
97 while ( /\b(\w\S+)(\s+\1)+\b/gi ) {
98 print "Duplicate $1 at paragraph $.\n";
54310121 99 }
100 }
68dc0745 101
102Here's code that finds sentences that begin with "From " (which would
103be mangled by many mailers):
104
105 $/ = ''; # read in more whole paragraph, not just one line
106 while ( <> ) {
107 while ( /^From /gm ) { # /m makes ^ match next to \n
108 print "leading from in paragraph $.\n";
109 }
110 }
111
112Here's code that finds everything between START and END in a paragraph:
113
114 undef $/; # read in whole file, not just one line or paragraph
115 while ( <> ) {
116 while ( /START(.*?)END/sm ) { # /s makes . cross line boundaries
117 print "$1\n";
118 }
119 }
120
121=head2 How can I pull out lines between two patterns that are themselves on different lines?
122
123You can use Perl's somewhat exotic C<..> operator (documented in
124L<perlop>):
125
126 perl -ne 'print if /START/ .. /END/' file1 file2 ...
127
128If you wanted text and not lines, you would use
129
130 perl -0777 -pe 'print "$1\n" while /START(.*?)END/gs' file1 file2 ...
131
132But if you want nested occurrences of C<START> through C<END>, you'll
133run up against the problem described in the question in this section
134on matching balanced text.
135
136=head2 I put a regular expression into $/ but it didn't work. What's wrong?
137
138$/ must be a string, not a regular expression. Awk has to be better
139for something. :-)
140
54310121 141Actually, you could do this if you don't mind reading the whole file into
68dc0745 142
143 undef $/;
144 @records = split /your_pattern/, <FH>;
145
3fe9a6f1 146The Net::Telnet module (available from CPAN) has the capability to
147wait for a pattern in the input stream, or timeout if it doesn't
148appear within a certain time.
149
150 ## Create a file with three lines.
151 open FH, ">file";
152 print FH "The first line\nThe second line\nThe third line\n";
153 close FH;
154
155 ## Get a read/write filehandle to it.
156 $fh = new FileHandle "+<file";
157
158 ## Attach it to a "stream" object.
159 use Net::Telnet;
160 $file = new Net::Telnet (-fhopen => $fh);
161
162 ## Search for the second line and print out the third.
163 $file->waitfor('/second line\n/');
164 print $file->getline;
165
68dc0745 166=head2 How do I substitute case insensitively on the LHS, but preserving case on the RHS?
167
168It depends on what you mean by "preserving case". The following
169script makes the substitution have the same case, letter by letter, as
170the original. If the substitution has more characters than the string
171being substituted, the case of the last character is used for the rest
172of the substitution.
173
174 # Original by Nathan Torkington, massaged by Jeffrey Friedl
175 #
176 sub preserve_case($$)
177 {
178 my ($old, $new) = @_;
179 my ($state) = 0; # 0 = no change; 1 = lc; 2 = uc
180 my ($i, $oldlen, $newlen, $c) = (0, length($old), length($new));
181 my ($len) = $oldlen < $newlen ? $oldlen : $newlen;
182
183 for ($i = 0; $i < $len; $i++) {
184 if ($c = substr($old, $i, 1), $c =~ /[\W\d_]/) {
185 $state = 0;
186 } elsif (lc $c eq $c) {
187 substr($new, $i, 1) = lc(substr($new, $i, 1));
188 $state = 1;
189 } else {
190 substr($new, $i, 1) = uc(substr($new, $i, 1));
191 $state = 2;
192 }
193 }
194 # finish up with any remaining new (for when new is longer than old)
195 if ($newlen > $oldlen) {
196 if ($state == 1) {
197 substr($new, $oldlen) = lc(substr($new, $oldlen));
198 } elsif ($state == 2) {
199 substr($new, $oldlen) = uc(substr($new, $oldlen));
200 }
201 }
202 return $new;
203 }
204
205 $a = "this is a TEsT case";
206 $a =~ s/(test)/preserve_case($1, "success")/gie;
207 print "$a\n";
208
209This prints:
210
211 this is a SUcCESS case
212
213=head2 How can I make C<\w> match accented characters?
214
215See L<perllocale>.
216
217=head2 How can I match a locale-smart version of C</[a-zA-Z]/>?
218
219One alphabetic character would be C</[^\W\d_]/>, no matter what locale
54310121 220you're in. Non-alphabetics would be C</[\W\d_]/> (assuming you don't
68dc0745 221consider an underscore a letter).
222
54310121 223=head2 How can I quote a variable to use in a regexp?
68dc0745 224
225The Perl parser will expand $variable and @variable references in
226regular expressions unless the delimiter is a single quote. Remember,
227too, that the right-hand side of a C<s///> substitution is considered
228a double-quoted string (see L<perlop> for more details). Remember
229also that any regexp special characters will be acted on unless you
230precede the substitution with \Q. Here's an example:
231
232 $string = "to die?";
233 $lhs = "die?";
234 $rhs = "sleep no more";
235
236 $string =~ s/\Q$lhs/$rhs/;
237 # $string is now "to sleep no more"
238
239Without the \Q, the regexp would also spuriously match "di".
240
241=head2 What is C</o> really for?
242
54310121 243Using a variable in a regular expression match forces a reevaluation
68dc0745 244(and perhaps recompilation) each time through. The C</o> modifier
245locks in the regexp the first time it's used. This always happens in a
246constant regular expression, and in fact, the pattern was compiled
247into the internal format at the same time your entire program was.
248
249Use of C</o> is irrelevant unless variable interpolation is used in
250the pattern, and if so, the regexp engine will neither know nor care
251whether the variables change after the pattern is evaluated the I<very
252first> time.
253
254C</o> is often used to gain an extra measure of efficiency by not
255performing subsequent evaluations when you know it won't matter
256(because you know the variables won't change), or more rarely, when
257you don't want the regexp to notice if they do.
258
259For example, here's a "paragrep" program:
260
261 $/ = ''; # paragraph mode
262 $pat = shift;
263 while (<>) {
264 print if /$pat/o;
265 }
266
267=head2 How do I use a regular expression to strip C style comments from a file?
268
269While this actually can be done, it's much harder than you'd think.
270For example, this one-liner
271
272 perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c
273
274will work in many but not all cases. You see, it's too simple-minded for
275certain kinds of C programs, in particular, those with what appear to be
276comments in quoted strings. For that, you'd need something like this,
277created by Jeffrey Friedl:
278
279 $/ = undef;
280 $_ = <>;
281 s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|\n+|.[^/"'\\]*)#$2#g;
282 print;
283
284This could, of course, be more legibly written with the C</x> modifier, adding
285whitespace and comments.
286
287=head2 Can I use Perl regular expressions to match balanced text?
288
289Although Perl regular expressions are more powerful than "mathematical"
290regular expressions, because they feature conveniences like backreferences
291(C<\1> and its ilk), they still aren't powerful enough. You still need
292to use non-regexp techniques to parse balanced text, such as the text
293enclosed between matching parentheses or braces, for example.
294
295An elaborate subroutine (for 7-bit ASCII only) to pull out balanced
296and possibly nested single chars, like C<`> and C<'>, C<{> and C<}>,
297or C<(> and C<)> can be found in
298http://www.perl.com/CPAN/authors/id/TOMC/scripts/pull_quotes.gz .
299
300The C::Scan module from CPAN contains such subs for internal usage,
301but they are undocumented.
302
303=head2 What does it mean that regexps are greedy? How can I get around it?
304
305Most people mean that greedy regexps match as much as they can.
306Technically speaking, it's actually the quantifiers (C<?>, C<*>, C<+>,
307C<{}>) that are greedy rather than the whole pattern; Perl prefers local
308greed and immediate gratification to overall greed. To get non-greedy
309versions of the same quantifiers, use (C<??>, C<*?>, C<+?>, C<{}?>).
310
311An example:
312
313 $s1 = $s2 = "I am very very cold";
314 $s1 =~ s/ve.*y //; # I am cold
315 $s2 =~ s/ve.*?y //; # I am very cold
316
317Notice how the second substitution stopped matching as soon as it
318encountered "y ". The C<*?> quantifier effectively tells the regular
319expression engine to find a match as quickly as possible and pass
320control on to whatever is next in line, like you would if you were
321playing hot potato.
322
323=head2 How do I process each word on each line?
324
325Use the split function:
326
327 while (<>) {
54310121 328 foreach $word ( split ) {
68dc0745 329 # do something with $word here
54310121 330 }
331 }
68dc0745 332
54310121 333Note that this isn't really a word in the English sense; it's just
334chunks of consecutive non-whitespace characters.
68dc0745 335
336To work with only alphanumeric sequences, you might consider
337
338 while (<>) {
339 foreach $word (m/(\w+)/g) {
340 # do something with $word here
341 }
342 }
343
344=head2 How can I print out a word-frequency or line-frequency summary?
345
346To do this, you have to parse out each word in the input stream. We'll
54310121 347pretend that by word you mean chunk of alphabetics, hyphens, or
348apostrophes, rather than the non-whitespace chunk idea of a word given
68dc0745 349in the previous question:
350
351 while (<>) {
352 while ( /(\b[^\W_\d][\w'-]+\b)/g ) { # misses "`sheep'"
353 $seen{$1}++;
54310121 354 }
355 }
68dc0745 356 while ( ($word, $count) = each %seen ) {
357 print "$count $word\n";
54310121 358 }
68dc0745 359
360If you wanted to do the same thing for lines, you wouldn't need a
361regular expression:
362
54310121 363 while (<>) {
68dc0745 364 $seen{$_}++;
54310121 365 }
68dc0745 366 while ( ($line, $count) = each %seen ) {
367 print "$count $line";
368 }
369
370If you want these output in a sorted order, see the section on Hashes.
371
372=head2 How can I do approximate matching?
373
374See the module String::Approx available from CPAN.
375
376=head2 How do I efficiently match many regular expressions at once?
377
378The following is super-inefficient:
379
380 while (<FH>) {
381 foreach $pat (@patterns) {
382 if ( /$pat/ ) {
383 # do something
384 }
385 }
386 }
387
388Instead, you either need to use one of the experimental Regexp extension
389modules from CPAN (which might well be overkill for your purposes),
390or else put together something like this, inspired from a routine
391in Jeffrey Friedl's book:
392
393 sub _bm_build {
394 my $condition = shift;
395 my @regexp = @_; # this MUST not be local(); need my()
396 my $expr = join $condition => map { "m/\$regexp[$_]/o" } (0..$#regexp);
397 my $match_func = eval "sub { $expr }";
398 die if $@; # propagate $@; this shouldn't happen!
399 return $match_func;
400 }
401
402 sub bm_and { _bm_build('&&', @_) }
403 sub bm_or { _bm_build('||', @_) }
404
405 $f1 = bm_and qw{
406 xterm
407 (?i)window
408 };
409
410 $f2 = bm_or qw{
411 \b[Ff]ree\b
412 \bBSD\B
413 (?i)sys(tem)?\s*[V5]\b
414 };
415
416 # feed me /etc/termcap, prolly
417 while ( <> ) {
418 print "1: $_" if &$f1;
419 print "2: $_" if &$f2;
420 }
421
422=head2 Why don't word-boundary searches with C<\b> work for me?
423
424Two common misconceptions are that C<\b> is a synonym for C<\s+>, and
425that it's the edge between whitespace characters and non-whitespace
426characters. Neither is correct. C<\b> is the place between a C<\w>
427character and a C<\W> character (that is, C<\b> is the edge of a
428"word"). It's a zero-width assertion, just like C<^>, C<$>, and all
429the other anchors, so it doesn't consume any characters. L<perlre>
430describes the behaviour of all the regexp metacharacters.
431
432Here are examples of the incorrect application of C<\b>, with fixes:
433
434 "two words" =~ /(\w+)\b(\w+)/; # WRONG
435 "two words" =~ /(\w+)\s+(\w+)/; # right
436
437 " =matchless= text" =~ /\b=(\w+)=\b/; # WRONG
438 " =matchless= text" =~ /=(\w+)=/; # right
439
440Although they may not do what you thought they did, C<\b> and C<\B>
441can still be quite useful. For an example of the correct use of
442C<\b>, see the example of matching duplicate words over multiple
443lines.
444
445An example of using C<\B> is the pattern C<\Bis\B>. This will find
446occurrences of "is" on the insides of words only, as in "thistle", but
447not "this" or "island".
448
449=head2 Why does using $&, $`, or $' slow my program down?
450
451Because once Perl sees that you need one of these variables anywhere
452in the program, it has to provide them on each and every pattern
453match. The same mechanism that handles these provides for the use of
454$1, $2, etc., so you pay the same price for each regexp that contains
455capturing parentheses. But if you never use $&, etc., in your script,
456then regexps I<without> capturing parentheses won't be penalized. So
457avoid $&, $', and $` if you can, but if you can't (and some algorithms
458really appreciate them), once you've used them once, use them at will,
459because you've already paid the price.
460
461=head2 What good is C<\G> in a regular expression?
462
463The notation C<\G> is used in a match or substitution in conjunction the
464C</g> modifier (and ignored if there's no C</g>) to anchor the regular
465expression to the point just past where the last match occurred, i.e. the
466pos() point.
467
468For example, suppose you had a line of text quoted in standard mail
469and Usenet notation, (that is, with leading C<E<gt>> characters), and
470you want change each leading C<E<gt>> into a corresponding C<:>. You
471could do so in this way:
472
473 s/^(>+)/':' x length($1)/gem;
474
475Or, using C<\G>, the much simpler (and faster):
476
477 s/\G>/:/g;
478
479A more sophisticated use might involve a tokenizer. The following
480lex-like example is courtesy of Jeffrey Friedl. It did not work in
4815.003 due to bugs in that release, but does work in 5.004 or better:
482
483 while (<>) {
484 chomp;
485 PARSER: {
486 m/ \G( \d+\b )/gx && do { print "number: $1\n"; redo; };
487 m/ \G( \w+ )/gx && do { print "word: $1\n"; redo; };
488 m/ \G( \s+ )/gx && do { print "space: $1\n"; redo; };
489 m/ \G( [^\w\d]+ )/gx && do { print "other: $1\n"; redo; };
490 }
491 }
492
493Of course, that could have been written as
494
495 while (<>) {
496 chomp;
497 PARSER: {
54310121 498 if ( /\G( \d+\b )/gx {
68dc0745 499 print "number: $1\n";
500 redo PARSER;
501 }
502 if ( /\G( \w+ )/gx {
503 print "word: $1\n";
504 redo PARSER;
505 }
506 if ( /\G( \s+ )/gx {
507 print "space: $1\n";
508 redo PARSER;
509 }
510 if ( /\G( [^\w\d]+ )/gx {
511 print "other: $1\n";
512 redo PARSER;
513 }
514 }
515 }
516
517But then you lose the vertical alignment of the regular expressions.
518
519=head2 Are Perl regexps DFAs or NFAs? Are they POSIX compliant?
520
521While it's true that Perl's regular expressions resemble the DFAs
522(deterministic finite automata) of the egrep(1) program, they are in
54310121 523fact implemented as NFAs (nondeterministic finite automata) to allow
68dc0745 524backtracking and backreferencing. And they aren't POSIX-style either,
525because those guarantee worst-case behavior for all cases. (It seems
526that some people prefer guarantees of consistency, even when what's
527guaranteed is slowness.) See the book "Mastering Regular Expressions"
528(from O'Reilly) by Jeffrey Friedl for all the details you could ever
529hope to know on these matters (a full citation appears in
530L<perlfaq2>).
531
532=head2 What's wrong with using grep or map in a void context?
533
534Strictly speaking, nothing. Stylistically speaking, it's not a good
535way to write maintainable code. That's because you're using these
536constructs not for their return values but rather for their
537side-effects, and side-effects can be mystifying. There's no void
538grep() that's not better written as a C<for> (well, C<foreach>,
539technically) loop.
540
54310121 541=head2 How can I match strings with multibyte characters?
68dc0745 542
543This is hard, and there's no good way. Perl does not directly support
544wide characters. It pretends that a byte and a character are
545synonymous. The following set of approaches was offered by Jeffrey
546Friedl, whose article in issue #5 of The Perl Journal talks about this
547very matter.
548
549Let's suppose you have some weird Martian encoding where pairs of ASCII
550uppercase letters encode single Martian letters (i.e. the two bytes
551"CV" make a single Martian letter, as do the two bytes "SG", "VS",
552"XX", etc.). Other bytes represent single characters, just like ASCII.
553
554So, the string of Martian "I am CVSGXX!" uses 12 bytes to encode the nine
555characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.
556
557Now, say you want to search for the single character C</GX/>. Perl
558doesn't know about Martian, so it'll find the two bytes "GX" in the
559"I am CVSGXX!" string, even though that character isn't there: it just
560looks like it is because "SG" is next to "XX", but there's no real "GX".
561This is a big problem.
562
563Here are a few ways, all painful, to deal with it:
564
3fe9a6f1 565 $martian =~ s/([A-Z][A-Z])/ $1 /g; # Make sure adjacent ``martian'' bytes
68dc0745 566 # are no longer adjacent.
567 print "found GX!\n" if $martian =~ /GX/;
568
569Or like this:
570
571 @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;
572 # above is conceptually similar to: @chars = $text =~ m/(.)/g;
573 #
574 foreach $char (@chars) {
575 print "found GX!\n", last if $char eq 'GX';
576 }
577
578Or like this:
579
580 while ($martian =~ m/\G([A-Z][A-Z]|.)/gs) { # \G probably unneeded
54310121 581 print "found GX!\n", last if $1 eq 'GX';
68dc0745 582 }
583
584Or like this:
585
586 die "sorry, Perl doesn't (yet) have Martian support )-:\n";
587
588In addition, a sample program which converts half-width to full-width
54310121 589katakana (in Shift-JIS or EUC encoding) is available from CPAN as
68dc0745 590
591=for Tom make it so
592
54310121 593There are many double (and multi) byte encodings commonly used these
68dc0745 594days. Some versions of these have 1-, 2-, 3-, and 4-byte characters,
595all mixed.
596
597=head1 AUTHOR AND COPYRIGHT
598
599Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
600All rights reserved. See L<perlfaq> for distribution information.