Commit | Line | Data |
68dc0745 |
1 | =head1 NAME |
2 | |
49d635f9 |
3 | perlfaq6 - Regular Expressions ($Revision: 1.18 $, $Date: 2002/10/30 18:44:21 $) |
68dc0745 |
4 | |
5 | =head1 DESCRIPTION |
6 | |
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 |
a6dd486b |
11 | this document (in L<perlfaq9>: ``How do I decode or create those %-encodings |
f5ba0729 |
12 | on the web'' and L<perlfaq4>: ``How do I determine whether a scalar is |
a6dd486b |
13 | a 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? |
68dc0745 |
16 | |
17 | Three techniques can make regular expressions maintainable and |
18 | understandable. |
19 | |
20 | =over 4 |
21 | |
d92eb7b0 |
22 | =item Comments Outside the Regex |
68dc0745 |
23 | |
24 | Describe what you're doing and how you're doing it, using normal Perl |
25 | comments. |
26 | |
27 | # turn the line into the first word, a colon, and the |
28 | # number of characters on the rest of the line |
5a964f20 |
29 | s/^(\w+)(.*)/ lc($1) . ":" . length($2) /meg; |
68dc0745 |
30 | |
d92eb7b0 |
31 | =item Comments Inside the Regex |
68dc0745 |
32 | |
d92eb7b0 |
33 | The C</x> modifier causes whitespace to be ignored in a regex pattern |
68dc0745 |
34 | (except in a character class), and also allows you to use normal |
35 | comments there, too. As you can imagine, whitespace and comments help |
36 | a lot. |
37 | |
38 | C</x> lets you turn this: |
39 | |
40 | s{<(?:[^>'"]*|".*?"|'.*?')+>}{}gs; |
41 | |
42 | into this: |
43 | |
44 | s{ < # opening angle bracket |
45 | (?: # Non-backreffing grouping paren |
46 | [^>'"] * # 0 or more things that are neither > nor ' nor " |
47 | | # or else |
48 | ".*?" # a section between double quotes (stingy match) |
49 | | # or else |
50 | '.*?' # a section between single quotes (stingy match) |
51 | ) + # all occurring one or more times |
52 | > # closing angle bracket |
53 | }{}gsx; # replace with nothing, i.e. delete |
54 | |
55 | It's still not quite so clear as prose, but it is very useful for |
56 | describing the meaning of each part of the pattern. |
57 | |
58 | =item Different Delimiters |
59 | |
60 | While we normally think of patterns as being delimited with C</> |
61 | characters, they can be delimited by almost any character. L<perlre> |
62 | describes this. For example, the C<s///> above uses braces as |
63 | delimiters. Selecting another delimiter can avoid quoting the |
64 | delimiter within the pattern: |
65 | |
66 | s/\/usr\/local/\/usr\/share/g; # bad delimiter choice |
67 | s#/usr/local#/usr/share#g; # better |
68 | |
69 | =back |
70 | |
71 | =head2 I'm having trouble matching over more than one line. What's wrong? |
72 | |
3392b9ec |
73 | Either you don't have more than one line in the string you're looking |
74 | at (probably), or else you aren't using the correct modifier(s) on |
75 | your pattern (possibly). |
68dc0745 |
76 | |
77 | There are many ways to get multiline data into a string. If you want |
78 | it to happen automatically while reading input, you'll want to set $/ |
79 | (probably to '' for paragraphs or C<undef> for the whole file) to |
80 | allow you to read more than one line at a time. |
81 | |
82 | Read L<perlre> to help you decide which of C</s> and C</m> (or both) |
83 | you might want to use: C</s> allows dot to include newline, and C</m> |
84 | allows caret and dollar to match next to a newline, not just at the |
85 | end of the string. You do need to make sure that you've actually |
86 | got a multiline string in there. |
87 | |
88 | For example, this program detects duplicate words, even when they span |
89 | line breaks (but not paragraph ones). For this example, we don't need |
90 | C</s> because we aren't using dot in a regular expression that we want |
91 | to cross line boundaries. Neither do we need C</m> because we aren't |
92 | wanting caret or dollar to match at any point inside the record next |
93 | to newlines. But it's imperative that $/ be set to something other |
94 | than the default, or else we won't actually ever have a multiline |
95 | record read in. |
96 | |
97 | $/ = ''; # read in more whole paragraph, not just one line |
98 | while ( <> ) { |
5a964f20 |
99 | while ( /\b([\w'-]+)(\s+\1)+\b/gi ) { # word starts alpha |
68dc0745 |
100 | print "Duplicate $1 at paragraph $.\n"; |
54310121 |
101 | } |
102 | } |
68dc0745 |
103 | |
104 | Here's code that finds sentences that begin with "From " (which would |
105 | be mangled by many mailers): |
106 | |
107 | $/ = ''; # read in more whole paragraph, not just one line |
108 | while ( <> ) { |
109 | while ( /^From /gm ) { # /m makes ^ match next to \n |
110 | print "leading from in paragraph $.\n"; |
111 | } |
112 | } |
113 | |
114 | Here's code that finds everything between START and END in a paragraph: |
115 | |
116 | undef $/; # read in whole file, not just one line or paragraph |
117 | while ( <> ) { |
fd89e497 |
118 | while ( /START(.*?)END/sgm ) { # /s makes . cross line boundaries |
68dc0745 |
119 | print "$1\n"; |
120 | } |
121 | } |
122 | |
123 | =head2 How can I pull out lines between two patterns that are themselves on different lines? |
124 | |
125 | You can use Perl's somewhat exotic C<..> operator (documented in |
126 | L<perlop>): |
127 | |
128 | perl -ne 'print if /START/ .. /END/' file1 file2 ... |
129 | |
130 | If you wanted text and not lines, you would use |
131 | |
65acb1b1 |
132 | perl -0777 -ne 'print "$1\n" while /START(.*?)END/gs' file1 file2 ... |
68dc0745 |
133 | |
134 | But if you want nested occurrences of C<START> through C<END>, you'll |
135 | run up against the problem described in the question in this section |
136 | on matching balanced text. |
137 | |
5a964f20 |
138 | Here's another example of using C<..>: |
139 | |
140 | while (<>) { |
141 | $in_header = 1 .. /^$/; |
142 | $in_body = /^$/ .. eof(); |
143 | # now choose between them |
144 | } continue { |
145 | reset if eof(); # fix $. |
146 | } |
147 | |
68dc0745 |
148 | =head2 I put a regular expression into $/ but it didn't work. What's wrong? |
149 | |
49d635f9 |
150 | As of Perl 5.8.0, $/ has to be a string. This may change in 5.10, |
151 | but don't get your hopes up. Until then, you can use these examples |
152 | if you really need to do this. |
153 | |
154 | Use the four argument form of sysread to continually add to |
155 | a buffer. After you add to the buffer, you check if you have a |
156 | complete line (using your regular expression). |
157 | |
158 | local $_ = ""; |
159 | while( sysread FH, $_, 8192, length ) { |
160 | while( s/^((?s).*?)your_pattern/ ) { |
161 | my $record = $1; |
162 | # do stuff here. |
163 | } |
164 | } |
165 | |
166 | You can do the same thing with foreach and a match using the |
167 | c flag and the \G anchor, if you do not mind your entire file |
168 | being in memory at the end. |
169 | |
170 | local $_ = ""; |
171 | while( sysread FH, $_, 8192, length ) { |
172 | foreach my $record ( m/\G((?s).*?)your_pattern/gc ) { |
173 | # do stuff here. |
174 | } |
175 | substr( $_, 0, pos ) = "" if pos; |
176 | } |
68dc0745 |
177 | |
3fe9a6f1 |
178 | |
a6dd486b |
179 | =head2 How do I substitute case insensitively on the LHS while preserving case on the RHS? |
68dc0745 |
180 | |
d92eb7b0 |
181 | Here's a lovely Perlish solution by Larry Rosler. It exploits |
182 | properties of bitwise xor on ASCII strings. |
183 | |
184 | $_= "this is a TEsT case"; |
185 | |
186 | $old = 'test'; |
187 | $new = 'success'; |
188 | |
575cc754 |
189 | s{(\Q$old\E)} |
d92eb7b0 |
190 | { uc $new | (uc $1 ^ $1) . |
191 | (uc(substr $1, -1) ^ substr $1, -1) x |
192 | (length($new) - length $1) |
193 | }egi; |
194 | |
195 | print; |
196 | |
8305e449 |
197 | And here it is as a subroutine, modeled after the above: |
d92eb7b0 |
198 | |
199 | sub preserve_case($$) { |
200 | my ($old, $new) = @_; |
201 | my $mask = uc $old ^ $old; |
202 | |
203 | uc $new | $mask . |
204 | substr($mask, -1) x (length($new) - length($old)) |
205 | } |
206 | |
207 | $a = "this is a TEsT case"; |
208 | $a =~ s/(test)/preserve_case($1, "success")/egi; |
209 | print "$a\n"; |
210 | |
211 | This prints: |
212 | |
213 | this is a SUcCESS case |
214 | |
74b9445a |
215 | As an alternative, to keep the case of the replacement word if it is |
216 | longer than the original, you can use this code, by Jeff Pinyan: |
217 | |
218 | sub preserve_case { |
219 | my ($from, $to) = @_; |
220 | my ($lf, $lt) = map length, @_; |
7207e29d |
221 | |
74b9445a |
222 | if ($lt < $lf) { $from = substr $from, 0, $lt } |
223 | else { $from .= substr $to, $lf } |
7207e29d |
224 | |
74b9445a |
225 | return uc $to | ($from ^ uc $from); |
226 | } |
227 | |
228 | This changes the sentence to "this is a SUcCess case." |
229 | |
d92eb7b0 |
230 | Just to show that C programmers can write C in any programming language, |
231 | if you prefer a more C-like solution, the following script makes the |
232 | substitution have the same case, letter by letter, as the original. |
233 | (It also happens to run about 240% slower than the Perlish solution runs.) |
234 | If the substitution has more characters than the string being substituted, |
235 | the case of the last character is used for the rest of the substitution. |
68dc0745 |
236 | |
237 | # Original by Nathan Torkington, massaged by Jeffrey Friedl |
238 | # |
239 | sub preserve_case($$) |
240 | { |
241 | my ($old, $new) = @_; |
242 | my ($state) = 0; # 0 = no change; 1 = lc; 2 = uc |
243 | my ($i, $oldlen, $newlen, $c) = (0, length($old), length($new)); |
244 | my ($len) = $oldlen < $newlen ? $oldlen : $newlen; |
245 | |
246 | for ($i = 0; $i < $len; $i++) { |
247 | if ($c = substr($old, $i, 1), $c =~ /[\W\d_]/) { |
248 | $state = 0; |
249 | } elsif (lc $c eq $c) { |
250 | substr($new, $i, 1) = lc(substr($new, $i, 1)); |
251 | $state = 1; |
252 | } else { |
253 | substr($new, $i, 1) = uc(substr($new, $i, 1)); |
254 | $state = 2; |
255 | } |
256 | } |
257 | # finish up with any remaining new (for when new is longer than old) |
258 | if ($newlen > $oldlen) { |
259 | if ($state == 1) { |
260 | substr($new, $oldlen) = lc(substr($new, $oldlen)); |
261 | } elsif ($state == 2) { |
262 | substr($new, $oldlen) = uc(substr($new, $oldlen)); |
263 | } |
264 | } |
265 | return $new; |
266 | } |
267 | |
5a964f20 |
268 | =head2 How can I make C<\w> match national character sets? |
68dc0745 |
269 | |
49d635f9 |
270 | Put C<use locale;> in your script. The \w character class is taken |
271 | from the current locale. |
272 | |
273 | See L<perllocale> for details. |
68dc0745 |
274 | |
275 | =head2 How can I match a locale-smart version of C</[a-zA-Z]/>? |
276 | |
49d635f9 |
277 | You can use the POSIX character class syntax C</[[:alpha:]]/> |
278 | documented in L<perlre>. |
279 | |
280 | No matter which locale you are in, the alphabetic characters are |
281 | the characters in \w without the digits and the underscore. |
282 | As a regex, that looks like C</[^\W\d_]/>. Its complement, |
283 | the non-alphabetics, is then everything in \W along with |
284 | the digits and the underscore, or C</[\W\d_]/>. |
68dc0745 |
285 | |
d92eb7b0 |
286 | =head2 How can I quote a variable to use in a regex? |
68dc0745 |
287 | |
288 | The Perl parser will expand $variable and @variable references in |
289 | regular expressions unless the delimiter is a single quote. Remember, |
79a522f5 |
290 | too, that the right-hand side of a C<s///> substitution is considered |
68dc0745 |
291 | a double-quoted string (see L<perlop> for more details). Remember |
d92eb7b0 |
292 | also that any regex special characters will be acted on unless you |
68dc0745 |
293 | precede the substitution with \Q. Here's an example: |
294 | |
295 | $string = "to die?"; |
296 | $lhs = "die?"; |
d92eb7b0 |
297 | $rhs = "sleep, no more"; |
68dc0745 |
298 | |
299 | $string =~ s/\Q$lhs/$rhs/; |
300 | # $string is now "to sleep no more" |
301 | |
d92eb7b0 |
302 | Without the \Q, the regex would also spuriously match "di". |
68dc0745 |
303 | |
304 | =head2 What is C</o> really for? |
305 | |
46fc3d4c |
306 | Using a variable in a regular expression match forces a re-evaluation |
a6dd486b |
307 | (and perhaps recompilation) each time the regular expression is |
308 | encountered. The C</o> modifier locks in the regex the first time |
309 | it's used. This always happens in a constant regular expression, and |
310 | in fact, the pattern was compiled into the internal format at the same |
311 | time your entire program was. |
68dc0745 |
312 | |
313 | Use of C</o> is irrelevant unless variable interpolation is used in |
d92eb7b0 |
314 | the pattern, and if so, the regex engine will neither know nor care |
68dc0745 |
315 | whether the variables change after the pattern is evaluated the I<very |
316 | first> time. |
317 | |
318 | C</o> is often used to gain an extra measure of efficiency by not |
319 | performing subsequent evaluations when you know it won't matter |
320 | (because you know the variables won't change), or more rarely, when |
d92eb7b0 |
321 | you don't want the regex to notice if they do. |
68dc0745 |
322 | |
323 | For example, here's a "paragrep" program: |
324 | |
325 | $/ = ''; # paragraph mode |
326 | $pat = shift; |
327 | while (<>) { |
328 | print if /$pat/o; |
329 | } |
330 | |
331 | =head2 How do I use a regular expression to strip C style comments from a file? |
332 | |
333 | While this actually can be done, it's much harder than you'd think. |
334 | For example, this one-liner |
335 | |
336 | perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c |
337 | |
338 | will work in many but not all cases. You see, it's too simple-minded for |
339 | certain kinds of C programs, in particular, those with what appear to be |
340 | comments in quoted strings. For that, you'd need something like this, |
d92eb7b0 |
341 | created by Jeffrey Friedl and later modified by Fred Curtis. |
68dc0745 |
342 | |
343 | $/ = undef; |
344 | $_ = <>; |
d92eb7b0 |
345 | s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#$2#gs |
68dc0745 |
346 | print; |
347 | |
348 | This could, of course, be more legibly written with the C</x> modifier, adding |
d92eb7b0 |
349 | whitespace and comments. Here it is expanded, courtesy of Fred Curtis. |
350 | |
351 | s{ |
352 | /\* ## Start of /* ... */ comment |
353 | [^*]*\*+ ## Non-* followed by 1-or-more *'s |
354 | ( |
355 | [^/*][^*]*\*+ |
356 | )* ## 0-or-more things which don't start with / |
357 | ## but do end with '*' |
358 | / ## End of /* ... */ comment |
359 | |
360 | | ## OR various things which aren't comments: |
361 | |
362 | ( |
363 | " ## Start of " ... " string |
364 | ( |
365 | \\. ## Escaped char |
366 | | ## OR |
367 | [^"\\] ## Non "\ |
368 | )* |
369 | " ## End of " ... " string |
370 | |
371 | | ## OR |
372 | |
373 | ' ## Start of ' ... ' string |
374 | ( |
375 | \\. ## Escaped char |
376 | | ## OR |
377 | [^'\\] ## Non '\ |
378 | )* |
379 | ' ## End of ' ... ' string |
380 | |
381 | | ## OR |
382 | |
383 | . ## Anything other char |
384 | [^/"'\\]* ## Chars which doesn't start a comment, string or escape |
385 | ) |
386 | }{$2}gxs; |
387 | |
388 | A slight modification also removes C++ comments: |
389 | |
390 | s#/\*[^*]*\*+([^/*][^*]*\*+)*/|//[^\n]*|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#$2#gs; |
68dc0745 |
391 | |
392 | =head2 Can I use Perl regular expressions to match balanced text? |
393 | |
8305e449 |
394 | Historically, Perl regular expressions were not capable of matching |
395 | balanced text. As of more recent versions of perl including 5.6.1 |
396 | experimental features have been added that make it possible to do this. |
397 | Look at the documentation for the (??{ }) construct in recent perlre manual |
398 | pages to see an example of matching balanced parentheses. Be sure to take |
399 | special notice of the warnings present in the manual before making use |
400 | of this feature. |
401 | |
402 | CPAN contains many modules that can be useful for matching text |
403 | depending on the context. Damian Conway provides some useful |
404 | patterns in Regexp::Common. The module Text::Balanced provides a |
405 | general solution to this problem. |
406 | |
407 | One of the common applications of balanced text matching is working |
408 | with XML and HTML. There are many modules available that support |
409 | these needs. Two examples are HTML::Parser and XML::Parser. There |
410 | are many others. |
68dc0745 |
411 | |
412 | An elaborate subroutine (for 7-bit ASCII only) to pull out balanced |
413 | and possibly nested single chars, like C<`> and C<'>, C<{> and C<}>, |
414 | or C<(> and C<)> can be found in |
a93751fa |
415 | http://www.cpan.org/authors/id/TOMC/scripts/pull_quotes.gz . |
68dc0745 |
416 | |
8305e449 |
417 | The C::Scan module from CPAN also contains such subs for internal use, |
68dc0745 |
418 | but they are undocumented. |
419 | |
d92eb7b0 |
420 | =head2 What does it mean that regexes are greedy? How can I get around it? |
68dc0745 |
421 | |
d92eb7b0 |
422 | Most people mean that greedy regexes match as much as they can. |
68dc0745 |
423 | Technically speaking, it's actually the quantifiers (C<?>, C<*>, C<+>, |
424 | C<{}>) that are greedy rather than the whole pattern; Perl prefers local |
425 | greed and immediate gratification to overall greed. To get non-greedy |
426 | versions of the same quantifiers, use (C<??>, C<*?>, C<+?>, C<{}?>). |
427 | |
428 | An example: |
429 | |
430 | $s1 = $s2 = "I am very very cold"; |
431 | $s1 =~ s/ve.*y //; # I am cold |
432 | $s2 =~ s/ve.*?y //; # I am very cold |
433 | |
434 | Notice how the second substitution stopped matching as soon as it |
435 | encountered "y ". The C<*?> quantifier effectively tells the regular |
436 | expression engine to find a match as quickly as possible and pass |
437 | control on to whatever is next in line, like you would if you were |
438 | playing hot potato. |
439 | |
f9ac83b8 |
440 | =head2 How do I process each word on each line? |
68dc0745 |
441 | |
442 | Use the split function: |
443 | |
444 | while (<>) { |
fc36a67e |
445 | foreach $word ( split ) { |
68dc0745 |
446 | # do something with $word here |
fc36a67e |
447 | } |
54310121 |
448 | } |
68dc0745 |
449 | |
54310121 |
450 | Note that this isn't really a word in the English sense; it's just |
451 | chunks of consecutive non-whitespace characters. |
68dc0745 |
452 | |
f1cbbd6e |
453 | To work with only alphanumeric sequences (including underscores), you |
454 | might consider |
68dc0745 |
455 | |
456 | while (<>) { |
457 | foreach $word (m/(\w+)/g) { |
458 | # do something with $word here |
459 | } |
460 | } |
461 | |
462 | =head2 How can I print out a word-frequency or line-frequency summary? |
463 | |
464 | To do this, you have to parse out each word in the input stream. We'll |
54310121 |
465 | pretend that by word you mean chunk of alphabetics, hyphens, or |
466 | apostrophes, rather than the non-whitespace chunk idea of a word given |
68dc0745 |
467 | in the previous question: |
468 | |
469 | while (<>) { |
470 | while ( /(\b[^\W_\d][\w'-]+\b)/g ) { # misses "`sheep'" |
471 | $seen{$1}++; |
54310121 |
472 | } |
473 | } |
68dc0745 |
474 | while ( ($word, $count) = each %seen ) { |
475 | print "$count $word\n"; |
54310121 |
476 | } |
68dc0745 |
477 | |
478 | If you wanted to do the same thing for lines, you wouldn't need a |
479 | regular expression: |
480 | |
fc36a67e |
481 | while (<>) { |
68dc0745 |
482 | $seen{$_}++; |
54310121 |
483 | } |
68dc0745 |
484 | while ( ($line, $count) = each %seen ) { |
485 | print "$count $line"; |
486 | } |
487 | |
a6dd486b |
488 | If you want these output in a sorted order, see L<perlfaq4>: ``How do I |
489 | sort a hash (optionally by value instead of key)?''. |
68dc0745 |
490 | |
491 | =head2 How can I do approximate matching? |
492 | |
493 | See the module String::Approx available from CPAN. |
494 | |
495 | =head2 How do I efficiently match many regular expressions at once? |
496 | |
65acb1b1 |
497 | The following is extremely inefficient: |
68dc0745 |
498 | |
65acb1b1 |
499 | # slow but obvious way |
500 | @popstates = qw(CO ON MI WI MN); |
501 | while (defined($line = <>)) { |
502 | for $state (@popstates) { |
503 | if ($line =~ /\b$state\b/i) { |
504 | print $line; |
505 | last; |
506 | } |
507 | } |
508 | } |
509 | |
510 | That's because Perl has to recompile all those patterns for each of |
511 | the lines of the file. As of the 5.005 release, there's a much better |
512 | approach, one which makes use of the new C<qr//> operator: |
513 | |
514 | # use spiffy new qr// operator, with /i flag even |
515 | use 5.005; |
516 | @popstates = qw(CO ON MI WI MN); |
517 | @poppats = map { qr/\b$_\b/i } @popstates; |
518 | while (defined($line = <>)) { |
519 | for $patobj (@poppats) { |
520 | print $line if $line =~ /$patobj/; |
521 | } |
68dc0745 |
522 | } |
523 | |
524 | =head2 Why don't word-boundary searches with C<\b> work for me? |
525 | |
a6dd486b |
526 | Two common misconceptions are that C<\b> is a synonym for C<\s+> and |
68dc0745 |
527 | that it's the edge between whitespace characters and non-whitespace |
528 | characters. Neither is correct. C<\b> is the place between a C<\w> |
529 | character and a C<\W> character (that is, C<\b> is the edge of a |
530 | "word"). It's a zero-width assertion, just like C<^>, C<$>, and all |
531 | the other anchors, so it doesn't consume any characters. L<perlre> |
d92eb7b0 |
532 | describes the behavior of all the regex metacharacters. |
68dc0745 |
533 | |
534 | Here are examples of the incorrect application of C<\b>, with fixes: |
535 | |
536 | "two words" =~ /(\w+)\b(\w+)/; # WRONG |
537 | "two words" =~ /(\w+)\s+(\w+)/; # right |
538 | |
539 | " =matchless= text" =~ /\b=(\w+)=\b/; # WRONG |
540 | " =matchless= text" =~ /=(\w+)=/; # right |
541 | |
542 | Although they may not do what you thought they did, C<\b> and C<\B> |
543 | can still be quite useful. For an example of the correct use of |
544 | C<\b>, see the example of matching duplicate words over multiple |
545 | lines. |
546 | |
547 | An example of using C<\B> is the pattern C<\Bis\B>. This will find |
548 | occurrences of "is" on the insides of words only, as in "thistle", but |
549 | not "this" or "island". |
550 | |
551 | =head2 Why does using $&, $`, or $' slow my program down? |
552 | |
a6dd486b |
553 | Once Perl sees that you need one of these variables anywhere in |
554 | the program, it provides them on each and every pattern match. |
65acb1b1 |
555 | The same mechanism that handles these provides for the use of $1, $2, |
d92eb7b0 |
556 | etc., so you pay the same price for each regex that contains capturing |
a6dd486b |
557 | parentheses. If you never use $&, etc., in your script, then regexes |
65acb1b1 |
558 | I<without> capturing parentheses won't be penalized. So avoid $&, $', |
559 | and $` if you can, but if you can't, once you've used them at all, use |
560 | them at will because you've already paid the price. Remember that some |
561 | algorithms really appreciate them. As of the 5.005 release. the $& |
562 | variable is no longer "expensive" the way the other two are. |
68dc0745 |
563 | |
564 | =head2 What good is C<\G> in a regular expression? |
565 | |
49d635f9 |
566 | You use the C<\G> anchor to start the next match on the same |
567 | string where the last match left off. The regular |
568 | expression engine cannot skip over any characters to find |
569 | the next match with this anchor, so C<\G> is similar to the |
570 | beginning of string anchor, C<^>. The C<\G> anchor is typically |
571 | used with the C<g> flag. It uses the value of pos() |
572 | as the position to start the next match. As the match |
573 | operator makes successive matches, it updates pos() with the |
574 | position of the next character past the last match (or the |
575 | first character of the next match, depending on how you like |
576 | to look at it). Each string has its own pos() value. |
577 | |
578 | Suppose you want to match all of consective pairs of digits |
579 | in a string like "1122a44" and stop matching when you |
580 | encounter non-digits. You want to match C<11> and C<22> but |
581 | the letter <a> shows up between C<22> and C<44> and you want |
582 | to stop at C<a>. Simply matching pairs of digits skips over |
583 | the C<a> and still matches C<44>. |
584 | |
585 | $_ = "1122a44"; |
586 | my @pairs = m/(\d\d)/g; # qw( 11 22 44 ) |
587 | |
588 | If you use the \G anchor, you force the match after C<22> to |
589 | start with the C<a>. The regular expression cannot match |
590 | there since it does not find a digit, so the next match |
591 | fails and the match operator returns the pairs it already |
592 | found. |
593 | |
594 | $_ = "1122a44"; |
595 | my @pairs = m/\G(\d\d)/g; # qw( 11 22 ) |
596 | |
597 | You can also use the C<\G> anchor in scalar context. You |
598 | still need the C<g> flag. |
599 | |
600 | $_ = "1122a44"; |
601 | while( m/\G(\d\d)/g ) |
602 | { |
603 | print "Found $1\n"; |
604 | } |
605 | |
606 | After the match fails at the letter C<a>, perl resets pos() |
607 | and the next match on the same string starts at the beginning. |
608 | |
609 | $_ = "1122a44"; |
610 | while( m/\G(\d\d)/g ) |
611 | { |
612 | print "Found $1\n"; |
613 | } |
614 | |
615 | print "Found $1 after while" if m/(\d\d)/g; # finds "11" |
616 | |
617 | You can disable pos() resets on fail with the C<c> flag. |
618 | Subsequent matches start where the last successful match |
619 | ended (the value of pos()) even if a match on the same |
620 | string as failed in the meantime. In this case, the match |
621 | after the while() loop starts at the C<a> (where the last |
622 | match stopped), and since it does not use any anchor it can |
623 | skip over the C<a> to find "44". |
624 | |
625 | $_ = "1122a44"; |
626 | while( m/\G(\d\d)/gc ) |
627 | { |
628 | print "Found $1\n"; |
629 | } |
630 | |
631 | print "Found $1 after while" if m/(\d\d)/g; # finds "44" |
632 | |
633 | Typically you use the C<\G> anchor with the C<c> flag |
634 | when you want to try a different match if one fails, |
635 | such as in a tokenizer. Jeffrey Friedl offers this example |
636 | which works in 5.004 or later. |
68dc0745 |
637 | |
638 | while (<>) { |
639 | chomp; |
640 | PARSER: { |
49d635f9 |
641 | m/ \G( \d+\b )/gcx && do { print "number: $1\n"; redo; }; |
642 | m/ \G( \w+ )/gcx && do { print "word: $1\n"; redo; }; |
643 | m/ \G( \s+ )/gcx && do { print "space: $1\n"; redo; }; |
644 | m/ \G( [^\w\d]+ )/gcx && do { print "other: $1\n"; redo; }; |
68dc0745 |
645 | } |
646 | } |
647 | |
49d635f9 |
648 | For each line, the PARSER loop first tries to match a series |
649 | of digits followed by a word boundary. This match has to |
650 | start at the place the last match left off (or the beginning |
651 | of the string on the first match). Since C<m/ \G( \d+\b |
652 | )/gcx> uses the C<c> flag, if the string does not match that |
653 | regular expression, perl does not reset pos() and the next |
654 | match starts at the same position to try a different |
655 | pattern. |
68dc0745 |
656 | |
d92eb7b0 |
657 | =head2 Are Perl regexes DFAs or NFAs? Are they POSIX compliant? |
68dc0745 |
658 | |
659 | While it's true that Perl's regular expressions resemble the DFAs |
660 | (deterministic finite automata) of the egrep(1) program, they are in |
46fc3d4c |
661 | fact implemented as NFAs (non-deterministic finite automata) to allow |
68dc0745 |
662 | backtracking and backreferencing. And they aren't POSIX-style either, |
663 | because those guarantee worst-case behavior for all cases. (It seems |
664 | that some people prefer guarantees of consistency, even when what's |
665 | guaranteed is slowness.) See the book "Mastering Regular Expressions" |
666 | (from O'Reilly) by Jeffrey Friedl for all the details you could ever |
667 | hope to know on these matters (a full citation appears in |
668 | L<perlfaq2>). |
669 | |
670 | =head2 What's wrong with using grep or map in a void context? |
671 | |
f05bbc40 |
672 | The problem is that both grep and map build a return list, |
673 | regardless of the context. This means you're making Perl go |
674 | to the trouble of building a list that you then just throw away. |
675 | If the list is large, you waste both time and space. If your |
676 | intent is to iterate over the list then use a for loop for this |
677 | purpose. |
68dc0745 |
678 | |
54310121 |
679 | =head2 How can I match strings with multibyte characters? |
68dc0745 |
680 | |
d9d154f2 |
681 | Starting from Perl 5.6 Perl has had some level of multibyte character |
682 | support. Perl 5.8 or later is recommended. Supported multibyte |
fe854a6f |
683 | character repertoires include Unicode, and legacy encodings |
d9d154f2 |
684 | through the Encode module. See L<perluniintro>, L<perlunicode>, |
685 | and L<Encode>. |
686 | |
687 | If you are stuck with older Perls, you can do Unicode with the |
688 | C<Unicode::String> module, and character conversions using the |
689 | C<Unicode::Map8> and C<Unicode::Map> modules. If you are using |
690 | Japanese encodings, you might try using the jperl 5.005_03. |
691 | |
692 | Finally, the following set of approaches was offered by Jeffrey |
693 | Friedl, whose article in issue #5 of The Perl Journal talks about |
694 | this very matter. |
68dc0745 |
695 | |
fc36a67e |
696 | Let's suppose you have some weird Martian encoding where pairs of |
697 | ASCII uppercase letters encode single Martian letters (i.e. the two |
698 | bytes "CV" make a single Martian letter, as do the two bytes "SG", |
699 | "VS", "XX", etc.). Other bytes represent single characters, just like |
700 | ASCII. |
68dc0745 |
701 | |
fc36a67e |
702 | So, the string of Martian "I am CVSGXX!" uses 12 bytes to encode the |
703 | nine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'. |
68dc0745 |
704 | |
705 | Now, say you want to search for the single character C</GX/>. Perl |
fc36a67e |
706 | doesn't know about Martian, so it'll find the two bytes "GX" in the "I |
707 | am CVSGXX!" string, even though that character isn't there: it just |
708 | looks like it is because "SG" is next to "XX", but there's no real |
709 | "GX". This is a big problem. |
68dc0745 |
710 | |
711 | Here are a few ways, all painful, to deal with it: |
712 | |
49d635f9 |
713 | $martian =~ s/([A-Z][A-Z])/ $1 /g; # Make sure adjacent ``martian'' |
714 | # bytes are no longer adjacent. |
68dc0745 |
715 | print "found GX!\n" if $martian =~ /GX/; |
716 | |
717 | Or like this: |
718 | |
719 | @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g; |
720 | # above is conceptually similar to: @chars = $text =~ m/(.)/g; |
721 | # |
722 | foreach $char (@chars) { |
723 | print "found GX!\n", last if $char eq 'GX'; |
724 | } |
725 | |
726 | Or like this: |
727 | |
728 | while ($martian =~ m/\G([A-Z][A-Z]|.)/gs) { # \G probably unneeded |
54310121 |
729 | print "found GX!\n", last if $1 eq 'GX'; |
68dc0745 |
730 | } |
731 | |
49d635f9 |
732 | Here's another, slightly less painful, way to do it from Benjamin |
733 | Goldberg: |
734 | |
735 | $martian =~ m/ |
736 | (?!<[A-Z]) |
737 | (?:[A-Z][A-Z])*? |
738 | GX |
739 | /x; |
740 | |
741 | This succeeds if the "martian" character GX is in the string, and fails |
742 | otherwise. If you don't like using (?!<), you can replace (?!<[A-Z]) |
743 | with (?:^|[^A-Z]). |
744 | |
745 | It does have the drawback of putting the wrong thing in $-[0] and $+[0], |
746 | but this usually can be worked around. |
68dc0745 |
747 | |
65acb1b1 |
748 | =head2 How do I match a pattern that is supplied by the user? |
749 | |
750 | Well, if it's really a pattern, then just use |
751 | |
752 | chomp($pattern = <STDIN>); |
753 | if ($line =~ /$pattern/) { } |
754 | |
a6dd486b |
755 | Alternatively, since you have no guarantee that your user entered |
65acb1b1 |
756 | a valid regular expression, trap the exception this way: |
757 | |
758 | if (eval { $line =~ /$pattern/ }) { } |
759 | |
a6dd486b |
760 | If all you really want to search for a string, not a pattern, |
65acb1b1 |
761 | then you should either use the index() function, which is made for |
762 | string searching, or if you can't be disabused of using a pattern |
763 | match on a non-pattern, then be sure to use C<\Q>...C<\E>, documented |
764 | in L<perlre>. |
765 | |
766 | $pattern = <STDIN>; |
767 | |
768 | open (FILE, $input) or die "Couldn't open input $input: $!; aborting"; |
769 | while (<FILE>) { |
770 | print if /\Q$pattern\E/; |
771 | } |
772 | close FILE; |
773 | |
68dc0745 |
774 | =head1 AUTHOR AND COPYRIGHT |
775 | |
0bc0ad85 |
776 | Copyright (c) 1997-2002 Tom Christiansen and Nathan Torkington. |
5a964f20 |
777 | All rights reserved. |
778 | |
5a7beb56 |
779 | This documentation is free; you can redistribute it and/or modify it |
780 | under the same terms as Perl itself. |
5a964f20 |
781 | |
782 | Irrespective of its distribution, all code examples in this file |
783 | are hereby placed into the public domain. You are permitted and |
784 | encouraged to use this code in your own programs for fun |
785 | or for profit as you see fit. A simple comment in the code giving |
786 | credit would be courteous but is not required. |