This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[inseparable changes from match from perl-5.003_93 to perl-5.003_94]
[perl5.git] / pod / perlfaq6.pod
CommitLineData
68dc0745 1=head1 NAME
2
3perlfaq6 - Regexps ($Revision: 1.14 $)
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
14=head2 How can I hope to use regular expressions without creating illegible and unmaintainable code?
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";
99 }
100 }
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
141Actually, you could do this if you don't mind reading the whole file into
142
143 undef $/;
144 @records = split /your_pattern/, <FH>;
145
146=head2 How do I substitute case insensitively on the LHS, but preserving case on the RHS?
147
148It depends on what you mean by "preserving case". The following
149script makes the substitution have the same case, letter by letter, as
150the original. If the substitution has more characters than the string
151being substituted, the case of the last character is used for the rest
152of the substitution.
153
154 # Original by Nathan Torkington, massaged by Jeffrey Friedl
155 #
156 sub preserve_case($$)
157 {
158 my ($old, $new) = @_;
159 my ($state) = 0; # 0 = no change; 1 = lc; 2 = uc
160 my ($i, $oldlen, $newlen, $c) = (0, length($old), length($new));
161 my ($len) = $oldlen < $newlen ? $oldlen : $newlen;
162
163 for ($i = 0; $i < $len; $i++) {
164 if ($c = substr($old, $i, 1), $c =~ /[\W\d_]/) {
165 $state = 0;
166 } elsif (lc $c eq $c) {
167 substr($new, $i, 1) = lc(substr($new, $i, 1));
168 $state = 1;
169 } else {
170 substr($new, $i, 1) = uc(substr($new, $i, 1));
171 $state = 2;
172 }
173 }
174 # finish up with any remaining new (for when new is longer than old)
175 if ($newlen > $oldlen) {
176 if ($state == 1) {
177 substr($new, $oldlen) = lc(substr($new, $oldlen));
178 } elsif ($state == 2) {
179 substr($new, $oldlen) = uc(substr($new, $oldlen));
180 }
181 }
182 return $new;
183 }
184
185 $a = "this is a TEsT case";
186 $a =~ s/(test)/preserve_case($1, "success")/gie;
187 print "$a\n";
188
189This prints:
190
191 this is a SUcCESS case
192
193=head2 How can I make C<\w> match accented characters?
194
195See L<perllocale>.
196
197=head2 How can I match a locale-smart version of C</[a-zA-Z]/>?
198
199One alphabetic character would be C</[^\W\d_]/>, no matter what locale
200you're in. Non-alphabetics would be C</[\W\d_]/> (assuming you don't
201consider an underscore a letter).
202
203=head2 How can I quote a variable to use in a regexp?
204
205The Perl parser will expand $variable and @variable references in
206regular expressions unless the delimiter is a single quote. Remember,
207too, that the right-hand side of a C<s///> substitution is considered
208a double-quoted string (see L<perlop> for more details). Remember
209also that any regexp special characters will be acted on unless you
210precede the substitution with \Q. Here's an example:
211
212 $string = "to die?";
213 $lhs = "die?";
214 $rhs = "sleep no more";
215
216 $string =~ s/\Q$lhs/$rhs/;
217 # $string is now "to sleep no more"
218
219Without the \Q, the regexp would also spuriously match "di".
220
221=head2 What is C</o> really for?
222
223Using a variable in a regular expression match forces a re-evaluation
224(and perhaps recompilation) each time through. The C</o> modifier
225locks in the regexp the first time it's used. This always happens in a
226constant regular expression, and in fact, the pattern was compiled
227into the internal format at the same time your entire program was.
228
229Use of C</o> is irrelevant unless variable interpolation is used in
230the pattern, and if so, the regexp engine will neither know nor care
231whether the variables change after the pattern is evaluated the I<very
232first> time.
233
234C</o> is often used to gain an extra measure of efficiency by not
235performing subsequent evaluations when you know it won't matter
236(because you know the variables won't change), or more rarely, when
237you don't want the regexp to notice if they do.
238
239For example, here's a "paragrep" program:
240
241 $/ = ''; # paragraph mode
242 $pat = shift;
243 while (<>) {
244 print if /$pat/o;
245 }
246
247=head2 How do I use a regular expression to strip C style comments from a file?
248
249While this actually can be done, it's much harder than you'd think.
250For example, this one-liner
251
252 perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c
253
254will work in many but not all cases. You see, it's too simple-minded for
255certain kinds of C programs, in particular, those with what appear to be
256comments in quoted strings. For that, you'd need something like this,
257created by Jeffrey Friedl:
258
259 $/ = undef;
260 $_ = <>;
261 s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|\n+|.[^/"'\\]*)#$2#g;
262 print;
263
264This could, of course, be more legibly written with the C</x> modifier, adding
265whitespace and comments.
266
267=head2 Can I use Perl regular expressions to match balanced text?
268
269Although Perl regular expressions are more powerful than "mathematical"
270regular expressions, because they feature conveniences like backreferences
271(C<\1> and its ilk), they still aren't powerful enough. You still need
272to use non-regexp techniques to parse balanced text, such as the text
273enclosed between matching parentheses or braces, for example.
274
275An elaborate subroutine (for 7-bit ASCII only) to pull out balanced
276and possibly nested single chars, like C<`> and C<'>, C<{> and C<}>,
277or C<(> and C<)> can be found in
278http://www.perl.com/CPAN/authors/id/TOMC/scripts/pull_quotes.gz .
279
280The C::Scan module from CPAN contains such subs for internal usage,
281but they are undocumented.
282
283=head2 What does it mean that regexps are greedy? How can I get around it?
284
285Most people mean that greedy regexps match as much as they can.
286Technically speaking, it's actually the quantifiers (C<?>, C<*>, C<+>,
287C<{}>) that are greedy rather than the whole pattern; Perl prefers local
288greed and immediate gratification to overall greed. To get non-greedy
289versions of the same quantifiers, use (C<??>, C<*?>, C<+?>, C<{}?>).
290
291An example:
292
293 $s1 = $s2 = "I am very very cold";
294 $s1 =~ s/ve.*y //; # I am cold
295 $s2 =~ s/ve.*?y //; # I am very cold
296
297Notice how the second substitution stopped matching as soon as it
298encountered "y ". The C<*?> quantifier effectively tells the regular
299expression engine to find a match as quickly as possible and pass
300control on to whatever is next in line, like you would if you were
301playing hot potato.
302
303=head2 How do I process each word on each line?
304
305Use the split function:
306
307 while (<>) {
308 foreach $word ( split ) {
309 # do something with $word here
310 }
311 }
312
313Note that this isn't really a word in the English sense; it's just
314chunks of consecutive non-whitespace characters.
315
316To work with only alphanumeric sequences, you might consider
317
318 while (<>) {
319 foreach $word (m/(\w+)/g) {
320 # do something with $word here
321 }
322 }
323
324=head2 How can I print out a word-frequency or line-frequency summary?
325
326To do this, you have to parse out each word in the input stream. We'll
327pretend that by word you mean chunk of alphabetics, hyphens, or
328apostrophes, rather than the non-whitespace chunk idea of a word given
329in the previous question:
330
331 while (<>) {
332 while ( /(\b[^\W_\d][\w'-]+\b)/g ) { # misses "`sheep'"
333 $seen{$1}++;
334 }
335 }
336 while ( ($word, $count) = each %seen ) {
337 print "$count $word\n";
338 }
339
340If you wanted to do the same thing for lines, you wouldn't need a
341regular expression:
342
343 while (<>) {
344 $seen{$_}++;
345 }
346 while ( ($line, $count) = each %seen ) {
347 print "$count $line";
348 }
349
350If you want these output in a sorted order, see the section on Hashes.
351
352=head2 How can I do approximate matching?
353
354See the module String::Approx available from CPAN.
355
356=head2 How do I efficiently match many regular expressions at once?
357
358The following is super-inefficient:
359
360 while (<FH>) {
361 foreach $pat (@patterns) {
362 if ( /$pat/ ) {
363 # do something
364 }
365 }
366 }
367
368Instead, you either need to use one of the experimental Regexp extension
369modules from CPAN (which might well be overkill for your purposes),
370or else put together something like this, inspired from a routine
371in Jeffrey Friedl's book:
372
373 sub _bm_build {
374 my $condition = shift;
375 my @regexp = @_; # this MUST not be local(); need my()
376 my $expr = join $condition => map { "m/\$regexp[$_]/o" } (0..$#regexp);
377 my $match_func = eval "sub { $expr }";
378 die if $@; # propagate $@; this shouldn't happen!
379 return $match_func;
380 }
381
382 sub bm_and { _bm_build('&&', @_) }
383 sub bm_or { _bm_build('||', @_) }
384
385 $f1 = bm_and qw{
386 xterm
387 (?i)window
388 };
389
390 $f2 = bm_or qw{
391 \b[Ff]ree\b
392 \bBSD\B
393 (?i)sys(tem)?\s*[V5]\b
394 };
395
396 # feed me /etc/termcap, prolly
397 while ( <> ) {
398 print "1: $_" if &$f1;
399 print "2: $_" if &$f2;
400 }
401
402=head2 Why don't word-boundary searches with C<\b> work for me?
403
404Two common misconceptions are that C<\b> is a synonym for C<\s+>, and
405that it's the edge between whitespace characters and non-whitespace
406characters. Neither is correct. C<\b> is the place between a C<\w>
407character and a C<\W> character (that is, C<\b> is the edge of a
408"word"). It's a zero-width assertion, just like C<^>, C<$>, and all
409the other anchors, so it doesn't consume any characters. L<perlre>
410describes the behaviour of all the regexp metacharacters.
411
412Here are examples of the incorrect application of C<\b>, with fixes:
413
414 "two words" =~ /(\w+)\b(\w+)/; # WRONG
415 "two words" =~ /(\w+)\s+(\w+)/; # right
416
417 " =matchless= text" =~ /\b=(\w+)=\b/; # WRONG
418 " =matchless= text" =~ /=(\w+)=/; # right
419
420Although they may not do what you thought they did, C<\b> and C<\B>
421can still be quite useful. For an example of the correct use of
422C<\b>, see the example of matching duplicate words over multiple
423lines.
424
425An example of using C<\B> is the pattern C<\Bis\B>. This will find
426occurrences of "is" on the insides of words only, as in "thistle", but
427not "this" or "island".
428
429=head2 Why does using $&, $`, or $' slow my program down?
430
431Because once Perl sees that you need one of these variables anywhere
432in the program, it has to provide them on each and every pattern
433match. The same mechanism that handles these provides for the use of
434$1, $2, etc., so you pay the same price for each regexp that contains
435capturing parentheses. But if you never use $&, etc., in your script,
436then regexps I<without> capturing parentheses won't be penalized. So
437avoid $&, $', and $` if you can, but if you can't (and some algorithms
438really appreciate them), once you've used them once, use them at will,
439because you've already paid the price.
440
441=head2 What good is C<\G> in a regular expression?
442
443The notation C<\G> is used in a match or substitution in conjunction the
444C</g> modifier (and ignored if there's no C</g>) to anchor the regular
445expression to the point just past where the last match occurred, i.e. the
446pos() point.
447
448For example, suppose you had a line of text quoted in standard mail
449and Usenet notation, (that is, with leading C<E<gt>> characters), and
450you want change each leading C<E<gt>> into a corresponding C<:>. You
451could do so in this way:
452
453 s/^(>+)/':' x length($1)/gem;
454
455Or, using C<\G>, the much simpler (and faster):
456
457 s/\G>/:/g;
458
459A more sophisticated use might involve a tokenizer. The following
460lex-like example is courtesy of Jeffrey Friedl. It did not work in
4615.003 due to bugs in that release, but does work in 5.004 or better:
462
463 while (<>) {
464 chomp;
465 PARSER: {
466 m/ \G( \d+\b )/gx && do { print "number: $1\n"; redo; };
467 m/ \G( \w+ )/gx && do { print "word: $1\n"; redo; };
468 m/ \G( \s+ )/gx && do { print "space: $1\n"; redo; };
469 m/ \G( [^\w\d]+ )/gx && do { print "other: $1\n"; redo; };
470 }
471 }
472
473Of course, that could have been written as
474
475 while (<>) {
476 chomp;
477 PARSER: {
478 if ( /\G( \d+\b )/gx {
479 print "number: $1\n";
480 redo PARSER;
481 }
482 if ( /\G( \w+ )/gx {
483 print "word: $1\n";
484 redo PARSER;
485 }
486 if ( /\G( \s+ )/gx {
487 print "space: $1\n";
488 redo PARSER;
489 }
490 if ( /\G( [^\w\d]+ )/gx {
491 print "other: $1\n";
492 redo PARSER;
493 }
494 }
495 }
496
497But then you lose the vertical alignment of the regular expressions.
498
499=head2 Are Perl regexps DFAs or NFAs? Are they POSIX compliant?
500
501While it's true that Perl's regular expressions resemble the DFAs
502(deterministic finite automata) of the egrep(1) program, they are in
503fact implemented as NFAs (non-deterministic finite automata) to allow
504backtracking and backreferencing. And they aren't POSIX-style either,
505because those guarantee worst-case behavior for all cases. (It seems
506that some people prefer guarantees of consistency, even when what's
507guaranteed is slowness.) See the book "Mastering Regular Expressions"
508(from O'Reilly) by Jeffrey Friedl for all the details you could ever
509hope to know on these matters (a full citation appears in
510L<perlfaq2>).
511
512=head2 What's wrong with using grep or map in a void context?
513
514Strictly speaking, nothing. Stylistically speaking, it's not a good
515way to write maintainable code. That's because you're using these
516constructs not for their return values but rather for their
517side-effects, and side-effects can be mystifying. There's no void
518grep() that's not better written as a C<for> (well, C<foreach>,
519technically) loop.
520
521=head2 How can I match strings with multi-byte characters?
522
523This is hard, and there's no good way. Perl does not directly support
524wide characters. It pretends that a byte and a character are
525synonymous. The following set of approaches was offered by Jeffrey
526Friedl, whose article in issue #5 of The Perl Journal talks about this
527very matter.
528
529Let's suppose you have some weird Martian encoding where pairs of ASCII
530uppercase letters encode single Martian letters (i.e. the two bytes
531"CV" make a single Martian letter, as do the two bytes "SG", "VS",
532"XX", etc.). Other bytes represent single characters, just like ASCII.
533
534So, the string of Martian "I am CVSGXX!" uses 12 bytes to encode the nine
535characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.
536
537Now, say you want to search for the single character C</GX/>. Perl
538doesn't know about Martian, so it'll find the two bytes "GX" in the
539"I am CVSGXX!" string, even though that character isn't there: it just
540looks like it is because "SG" is next to "XX", but there's no real "GX".
541This is a big problem.
542
543Here are a few ways, all painful, to deal with it:
544
545 $martian =~ s/([A-Z][A-Z])/ $1 /g; # Make sure adjacent ``maritan'' bytes
546 # are no longer adjacent.
547 print "found GX!\n" if $martian =~ /GX/;
548
549Or like this:
550
551 @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;
552 # above is conceptually similar to: @chars = $text =~ m/(.)/g;
553 #
554 foreach $char (@chars) {
555 print "found GX!\n", last if $char eq 'GX';
556 }
557
558Or like this:
559
560 while ($martian =~ m/\G([A-Z][A-Z]|.)/gs) { # \G probably unneeded
561 print "found GX!\n", last if $1 eq 'GX';
562 }
563
564Or like this:
565
566 die "sorry, Perl doesn't (yet) have Martian support )-:\n";
567
568In addition, a sample program which converts half-width to full-width
569katakana (in Shift-JIS or EUC encoding) is available from CPAN as
570
571=for Tom make it so
572
573There are many double- (and multi-) byte encodings commonly used these
574days. Some versions of these have 1-, 2-, 3-, and 4-byte characters,
575all mixed.
576
577=head1 AUTHOR AND COPYRIGHT
578
579Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
580All rights reserved. See L<perlfaq> for distribution information.