Install Perl 5.8.8
[msysgit.git] / mingw / html / pod / perlfaq6.html
blob5b6461cd9aad143d72655239d0177e0ae83a5351
1 <?xml version="1.0" ?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml">
4 <head>
5 <title>perlfaq6 - Regular Expressions</title>
6 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
7 <link rev="made" href="mailto:" />
8 </head>
10 <body style="background-color: white">
11 <table border="0" width="100%" cellspacing="0" cellpadding="3">
12 <tr><td class="block" style="background-color: #cccccc" valign="middle">
13 <big><strong><span class="block">&nbsp;perlfaq6 - Regular Expressions</span></strong></big>
14 </td></tr>
15 </table>
17 <p><a name="__index__"></a></p>
18 <!-- INDEX BEGIN -->
20 <ul>
22 <li><a href="#name">NAME</a></li>
23 <li><a href="#description">DESCRIPTION</a></li>
24 <ul>
26 <li><a href="#how_can_i_hope_to_use_regular_expressions_without_creating_illegible_and_unmaintainable_code">How can I hope to use regular expressions without creating illegible and unmaintainable code?</a></li>
27 <li><a href="#i_m_having_trouble_matching_over_more_than_one_line__what_s_wrong">I'm having trouble matching over more than one line. What's wrong?</a></li>
28 <li><a href="#how_can_i_pull_out_lines_between_two_patterns_that_are_themselves_on_different_lines">How can I pull out lines between two patterns that are themselves on different lines?</a></li>
29 <li><a href="#i_put_a_regular_expression_into____but_it_didn_t_work__what_s_wrong">I put a regular expression into $/ but it didn't work. What's wrong?</a></li>
30 <li><a href="#how_do_i_substitute_case_insensitively_on_the_lhs_while_preserving_case_on_the_rhs">How do I substitute case insensitively on the LHS while preserving case on the RHS?</a></li>
31 <li><a href="#how_can_i_make__w_match_national_character_sets">How can I make <code>\w</code> match national character sets?</a></li>
32 <li><a href="#how_can_i_match_a_localesmart_version_of___azaz__">How can I match a locale-smart version of <code>/[a-zA-Z]/</code>?</a></li>
33 <li><a href="#how_can_i_quote_a_variable_to_use_in_a_regex">How can I quote a variable to use in a regex?</a></li>
34 <li><a href="#what_is__o_really_for">What is <code>/o</code> really for?</a></li>
35 <li><a href="#how_do_i_use_a_regular_expression_to_strip_c_style_comments_from_a_file">How do I use a regular expression to strip C style comments from a file?</a></li>
36 <li><a href="#can_i_use_perl_regular_expressions_to_match_balanced_text">Can I use Perl regular expressions to match balanced text?</a></li>
37 <li><a href="#what_does_it_mean_that_regexes_are_greedy_how_can_i_get_around_it">What does it mean that regexes are greedy? How can I get around it?</a></li>
38 <li><a href="#how_do_i_process_each_word_on_each_line">How do I process each word on each line?</a></li>
39 <li><a href="#how_can_i_print_out_a_wordfrequency_or_linefrequency_summary">How can I print out a word-frequency or line-frequency summary?</a></li>
40 <li><a href="#how_can_i_do_approximate_matching">How can I do approximate matching?</a></li>
41 <li><a href="#how_do_i_efficiently_match_many_regular_expressions_at_once">How do I efficiently match many regular expressions at once?</a></li>
42 <li><a href="#why_don_t_wordboundary_searches_with__b_work_for_me">Why don't word-boundary searches with <code>\b</code> work for me?</a></li>
43 <li><a href="#why_does_using_________or____slow_my_program_down">Why does using $&amp;, $`, or $' slow my program down?</a></li>
44 <li><a href="#what_good_is__g_in_a_regular_expression">What good is <code>\G</code> in a regular expression?</a></li>
45 <li><a href="#are_perl_regexes_dfas_or_nfas_are_they_posix_compliant">Are Perl regexes DFAs or NFAs? Are they POSIX compliant?</a></li>
46 <li><a href="#what_s_wrong_with_using_grep_in_a_void_context">What's wrong with using grep in a void context?</a></li>
47 <li><a href="#how_can_i_match_strings_with_multibyte_characters">How can I match strings with multibyte characters?</a></li>
48 <li><a href="#how_do_i_match_a_pattern_that_is_supplied_by_the_user">How do I match a pattern that is supplied by the user?</a></li>
49 </ul>
51 <li><a href="#author_and_copyright">AUTHOR AND COPYRIGHT</a></li>
52 </ul>
53 <!-- INDEX END -->
55 <hr />
56 <p>
57 </p>
58 <h1><a name="name">NAME</a></h1>
59 <p>perlfaq6 - Regular Expressions ($Revision: 1.38 $, $Date: 2005/12/31 00:54:37 $)</p>
60 <p>
61 </p>
62 <hr />
63 <h1><a name="description">DESCRIPTION</a></h1>
64 <p>This section is surprisingly small because the rest of the FAQ is
65 littered with answers involving regular expressions. For example,
66 decoding a URL and checking whether something is a number are handled
67 with regular expressions, but those answers are found elsewhere in
68 this document (in <a href="file://C|\msysgit\mingw\html/pod/perlfaq9.html">the perlfaq9 manpage</a>: ``How do I decode or create those %-encodings
69 on the web'' and <a href="file://C|\msysgit\mingw\html/pod/perlfaq4.html">the perlfaq4 manpage</a>: ``How do I determine whether a scalar is
70 a number/whole/integer/float'', to be precise).</p>
71 <p>
72 </p>
73 <h2><a name="how_can_i_hope_to_use_regular_expressions_without_creating_illegible_and_unmaintainable_code_x_regex__legibility__x_regexp__legibility__x_regular_expression__legibility__x__x_">How can I hope to use regular expressions without creating illegible and unmaintainable code?
75 </a></h2>
76 <p>Three techniques can make regular expressions maintainable and
77 understandable.</p>
78 <dl>
79 <dt><strong><a name="item_comments_outside_the_regex">Comments Outside the Regex</a></strong>
81 <dd>
82 <p>Describe what you're doing and how you're doing it, using normal Perl
83 comments.</p>
84 </dd>
85 <dd>
86 <pre>
87 # turn the line into the first word, a colon, and the
88 # number of characters on the rest of the line
89 s/^(\w+)(.*)/ lc($1) . &quot;:&quot; . length($2) /meg;</pre>
90 </dd>
91 </li>
92 <dt><strong><a name="item_comments_inside_the_regex">Comments Inside the Regex</a></strong>
94 <dd>
95 <p>The <code>/x</code> modifier causes whitespace to be ignored in a regex pattern
96 (except in a character class), and also allows you to use normal
97 comments there, too. As you can imagine, whitespace and comments help
98 a lot.</p>
99 </dd>
100 <dd>
101 <p><code>/x</code> lets you turn this:</p>
102 </dd>
103 <dd>
104 <pre>
105 s{&lt;(?:[^&gt;'&quot;]*|&quot;.*?&quot;|'.*?')+&gt;}{}gs;</pre>
106 </dd>
107 <dd>
108 <p>into this:</p>
109 </dd>
110 <dd>
111 <pre>
112 s{ &lt; # opening angle bracket
113 (?: # Non-backreffing grouping paren
114 [^&gt;'&quot;] * # 0 or more things that are neither &gt; nor ' nor &quot;
115 | # or else
116 &quot;.*?&quot; # a section between double quotes (stingy match)
117 | # or else
118 '.*?' # a section between single quotes (stingy match)
119 ) + # all occurring one or more times
120 &gt; # closing angle bracket
121 }{}gsx; # replace with nothing, i.e. delete</pre>
122 </dd>
123 <dd>
124 <p>It's still not quite so clear as prose, but it is very useful for
125 describing the meaning of each part of the pattern.</p>
126 </dd>
127 </li>
128 <dt><strong><a name="item_different_delimiters">Different Delimiters</a></strong>
130 <dd>
131 <p>While we normally think of patterns as being delimited with <code>/</code>
132 characters, they can be delimited by almost any character. <a href="file://C|\msysgit\mingw\html/pod/perlre.html">the perlre manpage</a>
133 describes this. For example, the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_s_"><code>s///</code></a> above uses braces as
134 delimiters. Selecting another delimiter can avoid quoting the
135 delimiter within the pattern:</p>
136 </dd>
137 <dd>
138 <pre>
139 s/\/usr\/local/\/usr\/share/g; # bad delimiter choice
140 s#/usr/local#/usr/share#g; # better</pre>
141 </dd>
142 </li>
143 </dl>
145 </p>
146 <h2><a name="i_m_having_trouble_matching_over_more_than_one_line__what_s_wrong_x_regex__multiline__x_regexp__multiline__x_regular_expression__multiline_">I'm having trouble matching over more than one line. What's wrong?
147 </a></h2>
148 <p>Either you don't have more than one line in the string you're looking
149 at (probably), or else you aren't using the correct <code>modifier(s)</code> on
150 your pattern (possibly).</p>
151 <p>There are many ways to get multiline data into a string. If you want
152 it to happen automatically while reading input, you'll want to set $/
153 (probably to '' for paragraphs or <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_undef"><code>undef</code></a> for the whole file) to
154 allow you to read more than one line at a time.</p>
155 <p>Read <a href="file://C|\msysgit\mingw\html/pod/perlre.html">the perlre manpage</a> to help you decide which of <code>/s</code> and <code>/m</code> (or both)
156 you might want to use: <code>/s</code> allows dot to include newline, and <code>/m</code>
157 allows caret and dollar to match next to a newline, not just at the
158 end of the string. You do need to make sure that you've actually
159 got a multiline string in there.</p>
160 <p>For example, this program detects duplicate words, even when they span
161 line breaks (but not paragraph ones). For this example, we don't need
162 <code>/s</code> because we aren't using dot in a regular expression that we want
163 to cross line boundaries. Neither do we need <code>/m</code> because we aren't
164 wanting caret or dollar to match at any point inside the record next
165 to newlines. But it's imperative that $/ be set to something other
166 than the default, or else we won't actually ever have a multiline
167 record read in.</p>
168 <pre>
169 $/ = ''; # read in more whole paragraph, not just one line
170 while ( &lt;&gt; ) {
171 while ( /\b([\w'-]+)(\s+\1)+\b/gi ) { # word starts alpha
172 print &quot;Duplicate $1 at paragraph $.\n&quot;;
174 }</pre>
175 <p>Here's code that finds sentences that begin with ``From '' (which would
176 be mangled by many mailers):</p>
177 <pre>
178 $/ = ''; # read in more whole paragraph, not just one line
179 while ( &lt;&gt; ) {
180 while ( /^From /gm ) { # /m makes ^ match next to \n
181 print &quot;leading from in paragraph $.\n&quot;;
183 }</pre>
184 <p>Here's code that finds everything between START and END in a paragraph:</p>
185 <pre>
186 undef $/; # read in whole file, not just one line or paragraph
187 while ( &lt;&gt; ) {
188 while ( /START(.*?)END/sgm ) { # /s makes . cross line boundaries
189 print &quot;$1\n&quot;;
191 }</pre>
193 </p>
194 <h2><a name="how_can_i_pull_out_lines_between_two_patterns_that_are_themselves_on_different_lines_x____">How can I pull out lines between two patterns that are themselves on different lines?
195 </a></h2>
196 <p>You can use Perl's somewhat exotic <code>..</code> operator (documented in
197 <a href="file://C|\msysgit\mingw\html/pod/perlop.html">the perlop manpage</a>):</p>
198 <pre>
199 perl -ne 'print if /START/ .. /END/' file1 file2 ...</pre>
200 <p>If you wanted text and not lines, you would use</p>
201 <pre>
202 perl -0777 -ne 'print &quot;$1\n&quot; while /START(.*?)END/gs' file1 file2 ...</pre>
203 <p>But if you want nested occurrences of <code>START</code> through <code>END</code>, you'll
204 run up against the problem described in the question in this section
205 on matching balanced text.</p>
206 <p>Here's another example of using <code>..</code>:</p>
207 <pre>
208 while (&lt;&gt;) {
209 $in_header = 1 .. /^$/;
210 $in_body = /^$/ .. eof();
211 # now choose between them
212 } continue {
213 reset if eof(); # fix $.
214 }</pre>
216 </p>
217 <h2><a name="i_put_a_regular_expression_into____but_it_didn_t_work__what_s_wrong_x_____regexes_in__x__input_record_separator__regexes_in__x__rs__regexes_in_">I put a regular expression into $/ but it didn't work. What's wrong?
219 </a></h2>
220 <p>Up to Perl 5.8.0, $/ has to be a string. This may change in 5.10,
221 but don't get your hopes up. Until then, you can use these examples
222 if you really need to do this.</p>
223 <p>If you have File::Stream, this is easy.</p>
224 <pre>
225 use File::Stream;
226 my $stream = File::Stream-&gt;new(
227 $filehandle,
228 separator =&gt; qr/\s*,\s*/,
229 );</pre>
230 <pre>
231 print &quot;$_\n&quot; while &lt;$stream&gt;;</pre>
232 <p>If you don't have File::Stream, you have to do a little more work.</p>
233 <p>You can use the four argument form of sysread to continually add to
234 a buffer. After you add to the buffer, you check if you have a
235 complete line (using your regular expression).</p>
236 <pre>
237 local $_ = &quot;&quot;;
238 while( sysread FH, $_, 8192, length ) {
239 while( s/^((?s).*?)your_pattern/ ) {
240 my $record = $1;
241 # do stuff here.
243 }</pre>
244 <pre>
245 You can do the same thing with foreach and a match using the
246 c flag and the \G anchor, if you do not mind your entire file
247 being in memory at the end.</pre>
248 <pre>
249 local $_ = &quot;&quot;;
250 while( sysread FH, $_, 8192, length ) {
251 foreach my $record ( m/\G((?s).*?)your_pattern/gc ) {
252 # do stuff here.
254 substr( $_, 0, pos ) = &quot;&quot; if pos;
255 }</pre>
257 </p>
258 <h2><a name="how_do_i_substitute_case_insensitively_on_the_lhs_while_preserving_case_on_the_rhs_x_replace__case_preserving__x_substitute__case_preserving__x_substitution__case_preserving__x_s__case_preserving_">How do I substitute case insensitively on the LHS while preserving case on the RHS?
260 </a></h2>
261 <p>Here's a lovely Perlish solution by Larry Rosler. It exploits
262 properties of bitwise xor on ASCII strings.</p>
263 <pre>
264 $_= &quot;this is a TEsT case&quot;;</pre>
265 <pre>
266 $old = 'test';
267 $new = 'success';</pre>
268 <pre>
269 s{(\Q$old\E)}
270 { uc $new | (uc $1 ^ $1) .
271 (uc(substr $1, -1) ^ substr $1, -1) x
272 (length($new) - length $1)
273 }egi;</pre>
274 <pre>
275 print;</pre>
276 <p>And here it is as a subroutine, modeled after the above:</p>
277 <pre>
278 sub preserve_case($$) {
279 my ($old, $new) = @_;
280 my $mask = uc $old ^ $old;</pre>
281 <pre>
282 uc $new | $mask .
283 substr($mask, -1) x (length($new) - length($old))
284 }</pre>
285 <pre>
286 $a = &quot;this is a TEsT case&quot;;
287 $a =~ s/(test)/preserve_case($1, &quot;success&quot;)/egi;
288 print &quot;$a\n&quot;;</pre>
289 <p>This prints:</p>
290 <pre>
291 this is a SUcCESS case</pre>
292 <p>As an alternative, to keep the case of the replacement word if it is
293 longer than the original, you can use this code, by Jeff Pinyan:</p>
294 <pre>
295 sub preserve_case {
296 my ($from, $to) = @_;
297 my ($lf, $lt) = map length, @_;</pre>
298 <pre>
299 if ($lt &lt; $lf) { $from = substr $from, 0, $lt }
300 else { $from .= substr $to, $lf }</pre>
301 <pre>
302 return uc $to | ($from ^ uc $from);
303 }</pre>
304 <p>This changes the sentence to ``this is a SUcCess case.''</p>
305 <p>Just to show that C programmers can write C in any programming language,
306 if you prefer a more C-like solution, the following script makes the
307 substitution have the same case, letter by letter, as the original.
308 (It also happens to run about 240% slower than the Perlish solution runs.)
309 If the substitution has more characters than the string being substituted,
310 the case of the last character is used for the rest of the substitution.</p>
311 <pre>
312 # Original by Nathan Torkington, massaged by Jeffrey Friedl
314 sub preserve_case($$)
316 my ($old, $new) = @_;
317 my ($state) = 0; # 0 = no change; 1 = lc; 2 = uc
318 my ($i, $oldlen, $newlen, $c) = (0, length($old), length($new));
319 my ($len) = $oldlen &lt; $newlen ? $oldlen : $newlen;</pre>
320 <pre>
321 for ($i = 0; $i &lt; $len; $i++) {
322 if ($c = substr($old, $i, 1), $c =~ /[\W\d_]/) {
323 $state = 0;
324 } elsif (lc $c eq $c) {
325 substr($new, $i, 1) = lc(substr($new, $i, 1));
326 $state = 1;
327 } else {
328 substr($new, $i, 1) = uc(substr($new, $i, 1));
329 $state = 2;
332 # finish up with any remaining new (for when new is longer than old)
333 if ($newlen &gt; $oldlen) {
334 if ($state == 1) {
335 substr($new, $oldlen) = lc(substr($new, $oldlen));
336 } elsif ($state == 2) {
337 substr($new, $oldlen) = uc(substr($new, $oldlen));
340 return $new;
341 }</pre>
343 </p>
344 <h2><a name="how_can_i_make__w_match_national_character_sets_x__w_">How can I make <code>\w</code> match national character sets?
345 </a></h2>
346 <p>Put <code>use locale;</code> in your script. The \w character class is taken
347 from the current locale.</p>
348 <p>See <a href="file://C|\msysgit\mingw\html/pod/perllocale.html">the perllocale manpage</a> for details.</p>
350 </p>
351 <h2><a name="how_can_i_match_a_localesmart_version_of___azaz___x_alpha_">How can I match a locale-smart version of <code>/[a-zA-Z]/</code>?
352 </a></h2>
353 <p>You can use the POSIX character class syntax <code>/[[:alpha:]]/</code>
354 documented in <a href="file://C|\msysgit\mingw\html/pod/perlre.html">the perlre manpage</a>.</p>
355 <p>No matter which locale you are in, the alphabetic characters are
356 the characters in \w without the digits and the underscore.
357 As a regex, that looks like <code>/[^\W\d_]/</code>. Its complement,
358 the non-alphabetics, is then everything in \W along with
359 the digits and the underscore, or <code>/[\W\d_]/</code>.</p>
361 </p>
362 <h2><a name="how_can_i_quote_a_variable_to_use_in_a_regex_x_regex__escaping__x_regexp__escaping__x_regular_expression__escaping_">How can I quote a variable to use in a regex?
363 </a></h2>
364 <p>The Perl parser will expand $variable and @variable references in
365 regular expressions unless the delimiter is a single quote. Remember,
366 too, that the right-hand side of a <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_s_"><code>s///</code></a> substitution is considered
367 a double-quoted string (see <a href="file://C|\msysgit\mingw\html/pod/perlop.html">the perlop manpage</a> for more details). Remember
368 also that any regex special characters will be acted on unless you
369 precede the substitution with \Q. Here's an example:</p>
370 <pre>
371 $string = &quot;Placido P. Octopus&quot;;
372 $regex = &quot;P.&quot;;</pre>
373 <pre>
374 $string =~ s/$regex/Polyp/;
375 # $string is now &quot;Polypacido P. Octopus&quot;</pre>
376 <p>Because <code>.</code> is special in regular expressions, and can match any
377 single character, the regex <code>P.</code> here has matched the &lt;Pl&gt; in the
378 original string.</p>
379 <p>To escape the special meaning of <code>.</code>, we use <code>\Q</code>:</p>
380 <pre>
381 $string = &quot;Placido P. Octopus&quot;;
382 $regex = &quot;P.&quot;;</pre>
383 <pre>
384 $string =~ s/\Q$regex/Polyp/;
385 # $string is now &quot;Placido Polyp Octopus&quot;</pre>
386 <p>The use of <code>\Q</code> causes the &lt;.&gt; in the regex to be treated as a
387 regular character, so that <code>P.</code> matches a <code>P</code> followed by a dot.</p>
389 </p>
390 <h2><a name="what_is__o_really_for_x__o_">What is <code>/o</code> really for?
391 </a></h2>
392 <p>Using a variable in a regular expression match forces a re-evaluation
393 (and perhaps recompilation) each time the regular expression is
394 encountered. The <code>/o</code> modifier locks in the regex the first time
395 it's used. This always happens in a constant regular expression, and
396 in fact, the pattern was compiled into the internal format at the same
397 time your entire program was.</p>
398 <p>Use of <code>/o</code> is irrelevant unless variable interpolation is used in
399 the pattern, and if so, the regex engine will neither know nor care
400 whether the variables change after the pattern is evaluated the <em>very
401 first</em> time.</p>
402 <p><code>/o</code> is often used to gain an extra measure of efficiency by not
403 performing subsequent evaluations when you know it won't matter
404 (because you know the variables won't change), or more rarely, when
405 you don't want the regex to notice if they do.</p>
406 <p>For example, here's a ``paragrep'' program:</p>
407 <pre>
408 $/ = ''; # paragraph mode
409 $pat = shift;
410 while (&lt;&gt;) {
411 print if /$pat/o;
412 }</pre>
414 </p>
415 <h2><a name="how_do_i_use_a_regular_expression_to_strip_c_style_comments_from_a_file">How do I use a regular expression to strip C style comments from a file?</a></h2>
416 <p>While this actually can be done, it's much harder than you'd think.
417 For example, this one-liner</p>
418 <pre>
419 perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c</pre>
420 <p>will work in many but not all cases. You see, it's too simple-minded for
421 certain kinds of C programs, in particular, those with what appear to be
422 comments in quoted strings. For that, you'd need something like this,
423 created by Jeffrey Friedl and later modified by Fred Curtis.</p>
424 <pre>
425 $/ = undef;
426 $_ = &lt;&gt;;
427 s#/\*[^*]*\*+([^/*][^*]*\*+)*/|(&quot;(\\.|[^&quot;\\])*&quot;|'(\\.|[^'\\])*'|.[^/&quot;'\\]*)#defined $2 ? $2 : &quot;&quot;#gse;
428 print;</pre>
429 <p>This could, of course, be more legibly written with the <code>/x</code> modifier, adding
430 whitespace and comments. Here it is expanded, courtesy of Fred Curtis.</p>
431 <pre>
433 /\* ## Start of /* ... */ comment
434 [^*]*\*+ ## Non-* followed by 1-or-more *'s
436 [^/*][^*]*\*+
437 )* ## 0-or-more things which don't start with /
438 ## but do end with '*'
439 / ## End of /* ... */ comment</pre>
440 <pre>
441 | ## OR various things which aren't comments:</pre>
442 <pre>
444 &quot; ## Start of &quot; ... &quot; string
446 \\. ## Escaped char
447 | ## OR
448 [^&quot;\\] ## Non &quot;\
450 &quot; ## End of &quot; ... &quot; string</pre>
451 <pre>
452 | ## OR</pre>
453 <pre>
454 ' ## Start of ' ... ' string
456 \\. ## Escaped char
457 | ## OR
458 [^'\\] ## Non '\
460 ' ## End of ' ... ' string</pre>
461 <pre>
462 | ## OR</pre>
463 <pre>
464 . ## Anything other char
465 [^/&quot;'\\]* ## Chars which doesn't start a comment, string or escape
467 }{defined $2 ? $2 : &quot;&quot;}gxse;</pre>
468 <p>A slight modification also removes C++ comments:</p>
469 <pre>
470 s#/\*[^*]*\*+([^/*][^*]*\*+)*/|//[^\n]*|(&quot;(\\.|[^&quot;\\])*&quot;|'(\\.|[^'\\])*'|.[^/&quot;'\\]*)#defined $2 ? $2 : &quot;&quot;#gse;</pre>
472 </p>
473 <h2><a name="can_i_use_perl_regular_expressions_to_match_balanced_text_x_regex__matching_balanced_test__x_regexp__matching_balanced_test__x_regular_expression__matching_balanced_test_">Can I use Perl regular expressions to match balanced text?
475 </a></h2>
476 <p>Historically, Perl regular expressions were not capable of matching
477 balanced text. As of more recent versions of perl including 5.6.1
478 experimental features have been added that make it possible to do this.
479 Look at the documentation for the (??{ }) construct in recent perlre manual
480 pages to see an example of matching balanced parentheses. Be sure to take
481 special notice of the warnings present in the manual before making use
482 of this feature.</p>
483 <p>CPAN contains many modules that can be useful for matching text
484 depending on the context. Damian Conway provides some useful
485 patterns in Regexp::Common. The module Text::Balanced provides a
486 general solution to this problem.</p>
487 <p>One of the common applications of balanced text matching is working
488 with XML and HTML. There are many modules available that support
489 these needs. Two examples are HTML::Parser and XML::Parser. There
490 are many others.</p>
491 <p>An elaborate subroutine (for 7-bit ASCII only) to pull out balanced
492 and possibly nested single chars, like <code>`</code> and <code>'</code>, <code>{</code> and <code>}</code>,
493 or <code>(</code> and <code>)</code> can be found in
494 <a href="http://www.cpan.org/authors/id/TOMC/scripts/pull_quotes.gz">http://www.cpan.org/authors/id/TOMC/scripts/pull_quotes.gz</a> .</p>
495 <p>The C::Scan module from CPAN also contains such subs for internal use,
496 but they are undocumented.</p>
498 </p>
499 <h2><a name="what_does_it_mean_that_regexes_are_greedy_how_can_i_get_around_it_x_greedy__x_greediness_">What does it mean that regexes are greedy? How can I get around it?
500 </a></h2>
501 <p>Most people mean that greedy regexes match as much as they can.
502 Technically speaking, it's actually the quantifiers (<code>?</code>, <code>*</code>, <code>+</code>,
503 <code>{}</code>) that are greedy rather than the whole pattern; Perl prefers local
504 greed and immediate gratification to overall greed. To get non-greedy
505 versions of the same quantifiers, use (<code>??</code>, <code>*?</code>, <code>+?</code>, <code>{}?</code>).</p>
506 <p>An example:</p>
507 <pre>
508 $s1 = $s2 = &quot;I am very very cold&quot;;
509 $s1 =~ s/ve.*y //; # I am cold
510 $s2 =~ s/ve.*?y //; # I am very cold</pre>
511 <p>Notice how the second substitution stopped matching as soon as it
512 encountered ``y ''. The <code>*?</code> quantifier effectively tells the regular
513 expression engine to find a match as quickly as possible and pass
514 control on to whatever is next in line, like you would if you were
515 playing hot potato.</p>
517 </p>
518 <h2><a name="how_do_i_process_each_word_on_each_line_x_word_">How do I process each word on each line?
519 </a></h2>
520 <p>Use the split function:</p>
521 <pre>
522 while (&lt;&gt;) {
523 foreach $word ( split ) {
524 # do something with $word here
526 }</pre>
527 <p>Note that this isn't really a word in the English sense; it's just
528 chunks of consecutive non-whitespace characters.</p>
529 <p>To work with only alphanumeric sequences (including underscores), you
530 might consider</p>
531 <pre>
532 while (&lt;&gt;) {
533 foreach $word (m/(\w+)/g) {
534 # do something with $word here
536 }</pre>
538 </p>
539 <h2><a name="how_can_i_print_out_a_wordfrequency_or_linefrequency_summary">How can I print out a word-frequency or line-frequency summary?</a></h2>
540 <p>To do this, you have to parse out each word in the input stream. We'll
541 pretend that by word you mean chunk of alphabetics, hyphens, or
542 apostrophes, rather than the non-whitespace chunk idea of a word given
543 in the previous question:</p>
544 <pre>
545 while (&lt;&gt;) {
546 while ( /(\b[^\W_\d][\w'-]+\b)/g ) { # misses &quot;`sheep'&quot;
547 $seen{$1}++;
550 while ( ($word, $count) = each %seen ) {
551 print &quot;$count $word\n&quot;;
552 }</pre>
553 <p>If you wanted to do the same thing for lines, you wouldn't need a
554 regular expression:</p>
555 <pre>
556 while (&lt;&gt;) {
557 $seen{$_}++;
559 while ( ($line, $count) = each %seen ) {
560 print &quot;$count $line&quot;;
561 }</pre>
562 <p>If you want these output in a sorted order, see <a href="file://C|\msysgit\mingw\html/pod/perlfaq4.html">the perlfaq4 manpage</a>: ``How do I
563 sort a hash (optionally by value instead of key)?''.</p>
565 </p>
566 <h2><a name="how_can_i_do_approximate_matching_x_match__approximate__x_matching__approximate_">How can I do approximate matching?
567 </a></h2>
568 <p>See the module String::Approx available from CPAN.</p>
570 </p>
571 <h2><a name="how_do_i_efficiently_match_many_regular_expressions_at_once_x_regex__efficiency__x_regexp__efficiency__x_regular_expression__efficiency_">How do I efficiently match many regular expressions at once?
573 </a></h2>
574 <p>( contributed by brian d foy )</p>
575 <p>Avoid asking Perl to compile a regular expression every time
576 you want to match it. In this example, perl must recompile
577 the regular expression for every iteration of the <code>foreach()</code>
578 loop since it has no way to know what $pattern will be.</p>
579 <pre>
580 @patterns = qw( foo bar baz );</pre>
581 <pre>
582 LINE: while( &lt;&gt; )
584 foreach $pattern ( @patterns )
586 print if /\b$pattern\b/i;
587 next LINE;
589 }</pre>
590 <p>The qr// operator showed up in perl 5.005. It compiles a
591 regular expression, but doesn't apply it. When you use the
592 pre-compiled version of the regex, perl does less work. In
593 this example, I inserted a <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_map"><code>map()</code></a> to turn each pattern into
594 its pre-compiled form. The rest of the script is the same,
595 but faster.</p>
596 <pre>
597 @patterns = map { qr/\b$_\b/i } qw( foo bar baz );</pre>
598 <pre>
599 LINE: while( &lt;&gt; )
601 foreach $pattern ( @patterns )
603 print if /\b$pattern\b/i;
604 next LINE;
606 }</pre>
607 <p>In some cases, you may be able to make several patterns into
608 a single regular expression. Beware of situations that require
609 backtracking though.</p>
610 <pre>
611 $regex = join '|', qw( foo bar baz );</pre>
612 <pre>
613 LINE: while( &lt;&gt; )
615 print if /\b(?:$regex)\b/i;
616 }</pre>
617 <p>For more details on regular expression efficiency, see Mastering
618 Regular Expressions by Jeffrey Freidl. He explains how regular
619 expressions engine work and why some patterns are surprisingly
620 inefficient. Once you understand how perl applies regular
621 expressions, you can tune them for individual situations.</p>
623 </p>
624 <h2><a name="why_don_t_wordboundary_searches_with__b_work_for_me_x__b_">Why don't word-boundary searches with <code>\b</code> work for me?
625 </a></h2>
626 <p>(contributed by brian d foy)</p>
627 <p>Ensure that you know what \b really does: it's the boundary between a
628 word character, \w, and something that isn't a word character. That
629 thing that isn't a word character might be \W, but it can also be the
630 start or end of the string.</p>
631 <p>It's not (not!) the boundary between whitespace and non-whitespace,
632 and it's not the stuff between words we use to create sentences.</p>
633 <p>In regex speak, a word boundary (\b) is a ``zero width assertion'',
634 meaning that it doesn't represent a character in the string, but a
635 condition at a certain position.</p>
636 <p>For the regular expression, /\bPerl\b/, there has to be a word
637 boundary before the ``P'' and after the ``l''. As long as something other
638 than a word character precedes the ``P'' and succeeds the ``l'', the
639 pattern will match. These strings match /\bPerl\b/.</p>
640 <pre>
641 &quot;Perl&quot; # no word char before P or after l
642 &quot;Perl &quot; # same as previous (space is not a word char)
643 &quot;'Perl'&quot; # the ' char is not a word char
644 &quot;Perl's&quot; # no word char before P, non-word char after &quot;l&quot;</pre>
645 <p>These strings do not match /\bPerl\b/.</p>
646 <pre>
647 &quot;Perl_&quot; # _ is a word char!
648 &quot;Perler&quot; # no word char before P, but one after l</pre>
649 <p>You don't have to use \b to match words though. You can look for
650 non-word characters surrounded by word characters. These strings
651 match the pattern /\b'\b/.</p>
652 <pre>
653 &quot;don't&quot; # the ' char is surrounded by &quot;n&quot; and &quot;t&quot;
654 &quot;qep'a'&quot; # the ' char is surrounded by &quot;p&quot; and &quot;a&quot;</pre>
655 <p>These strings do not match /\b'\b/.</p>
656 <pre>
657 &quot;foo'&quot; # there is no word char after non-word '</pre>
658 <p>You can also use the complement of \b, \B, to specify that there
659 should not be a word boundary.</p>
660 <p>In the pattern /\Bam\B/, there must be a word character before the ``a''
661 and after the ``m''. These patterns match /\Bam\B/:</p>
662 <pre>
663 &quot;llama&quot; # &quot;am&quot; surrounded by word chars
664 &quot;Samuel&quot; # same</pre>
665 <p>These strings do not match /\Bam\B/</p>
666 <pre>
667 &quot;Sam&quot; # no word boundary before &quot;a&quot;, but one after &quot;m&quot;
668 &quot;I am Sam&quot; # &quot;am&quot; surrounded by non-word chars</pre>
670 </p>
671 <h2><a name="why_does_using_________or____slow_my_program_down_x__match__x_____x__postmatch__x_____x__prematch__x____">Why does using $&amp;, $`, or $' slow my program down?
672 </a></h2>
673 <p>(contributed by Anno Siegel)</p>
674 <p>Once Perl sees that you need one of these variables anywhere in the
675 program, it provides them on each and every pattern match. That means
676 that on every pattern match the entire string will be copied, part of it
677 to $`, part to $&amp;, and part to $'. Thus the penalty is most severe with
678 long strings and patterns that match often. Avoid $&amp;, $', and $` if you
679 can, but if you can't, once you've used them at all, use them at will
680 because you've already paid the price. Remember that some algorithms
681 really appreciate them. As of the 5.005 release, the $&amp; variable is no
682 longer ``expensive'' the way the other two are.</p>
683 <p>Since Perl 5.6.1 the special variables @- and @+ can functionally replace
684 $`, $&amp; and $'. These arrays contain pointers to the beginning and end
685 of each match (see perlvar for the full story), so they give you
686 essentially the same information, but without the risk of excessive
687 string copying.</p>
689 </p>
690 <h2><a name="what_good_is__g_in_a_regular_expression_x__g_">What good is <code>\G</code> in a regular expression?
691 </a></h2>
692 <p>You use the <code>\G</code> anchor to start the next match on the same
693 string where the last match left off. The regular
694 expression engine cannot skip over any characters to find
695 the next match with this anchor, so <code>\G</code> is similar to the
696 beginning of string anchor, <code>^</code>. The <code>\G</code> anchor is typically
697 used with the <code>g</code> flag. It uses the value of <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_pos"><code>pos()</code></a>
698 as the position to start the next match. As the match
699 operator makes successive matches, it updates <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_pos"><code>pos()</code></a> with the
700 position of the next character past the last match (or the
701 first character of the next match, depending on how you like
702 to look at it). Each string has its own <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_pos"><code>pos()</code></a> value.</p>
703 <p>Suppose you want to match all of consective pairs of digits
704 in a string like ``1122a44'' and stop matching when you
705 encounter non-digits. You want to match <code>11</code> and <code>22</code> but
706 the letter &lt;a&gt; shows up between <code>22</code> and <code>44</code> and you want
707 to stop at <code>a</code>. Simply matching pairs of digits skips over
708 the <code>a</code> and still matches <code>44</code>.</p>
709 <pre>
710 $_ = &quot;1122a44&quot;;
711 my @pairs = m/(\d\d)/g; # qw( 11 22 44 )</pre>
712 <p>If you use the \G anchor, you force the match after <code>22</code> to
713 start with the <code>a</code>. The regular expression cannot match
714 there since it does not find a digit, so the next match
715 fails and the match operator returns the pairs it already
716 found.</p>
717 <pre>
718 $_ = &quot;1122a44&quot;;
719 my @pairs = m/\G(\d\d)/g; # qw( 11 22 )</pre>
720 <p>You can also use the <code>\G</code> anchor in scalar context. You
721 still need the <code>g</code> flag.</p>
722 <pre>
723 $_ = &quot;1122a44&quot;;
724 while( m/\G(\d\d)/g )
726 print &quot;Found $1\n&quot;;
727 }</pre>
728 <p>After the match fails at the letter <code>a</code>, perl resets <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_pos"><code>pos()</code></a>
729 and the next match on the same string starts at the beginning.</p>
730 <pre>
731 $_ = &quot;1122a44&quot;;
732 while( m/\G(\d\d)/g )
734 print &quot;Found $1\n&quot;;
735 }</pre>
736 <pre>
737 print &quot;Found $1 after while&quot; if m/(\d\d)/g; # finds &quot;11&quot;</pre>
738 <p>You can disable <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_pos"><code>pos()</code></a> resets on fail with the <code>c</code> flag.
739 Subsequent matches start where the last successful match
740 ended (the value of <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_pos"><code>pos())</code></a> even if a match on the same
741 string as failed in the meantime. In this case, the match
742 after the <code>while()</code> loop starts at the <code>a</code> (where the last
743 match stopped), and since it does not use any anchor it can
744 skip over the <code>a</code> to find ``44''.</p>
745 <pre>
746 $_ = &quot;1122a44&quot;;
747 while( m/\G(\d\d)/gc )
749 print &quot;Found $1\n&quot;;
750 }</pre>
751 <pre>
752 print &quot;Found $1 after while&quot; if m/(\d\d)/g; # finds &quot;44&quot;</pre>
753 <p>Typically you use the <code>\G</code> anchor with the <code>c</code> flag
754 when you want to try a different match if one fails,
755 such as in a tokenizer. Jeffrey Friedl offers this example
756 which works in 5.004 or later.</p>
757 <pre>
758 while (&lt;&gt;) {
759 chomp;
760 PARSER: {
761 m/ \G( \d+\b )/gcx &amp;&amp; do { print &quot;number: $1\n&quot;; redo; };
762 m/ \G( \w+ )/gcx &amp;&amp; do { print &quot;word: $1\n&quot;; redo; };
763 m/ \G( \s+ )/gcx &amp;&amp; do { print &quot;space: $1\n&quot;; redo; };
764 m/ \G( [^\w\d]+ )/gcx &amp;&amp; do { print &quot;other: $1\n&quot;; redo; };
766 }</pre>
767 <p>For each line, the PARSER loop first tries to match a series
768 of digits followed by a word boundary. This match has to
769 start at the place the last match left off (or the beginning
770 of the string on the first match). Since <code>m/ \G( \d+\b
771 )/gcx</code> uses the <code>c</code> flag, if the string does not match that
772 regular expression, perl does not reset <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_pos"><code>pos()</code></a> and the next
773 match starts at the same position to try a different
774 pattern.</p>
776 </p>
777 <h2><a name="are_perl_regexes_dfas_or_nfas_are_they_posix_compliant_x_dfa__x_nfa__x_posix_">Are Perl regexes DFAs or NFAs? Are they POSIX compliant?
778 </a></h2>
779 <p>While it's true that Perl's regular expressions resemble the DFAs
780 (deterministic finite automata) of the <code>egrep(1)</code> program, they are in
781 fact implemented as NFAs (non-deterministic finite automata) to allow
782 backtracking and backreferencing. And they aren't POSIX-style either,
783 because those guarantee worst-case behavior for all cases. (It seems
784 that some people prefer guarantees of consistency, even when what's
785 guaranteed is slowness.) See the book ``Mastering Regular Expressions''
786 (from O'Reilly) by Jeffrey Friedl for all the details you could ever
787 hope to know on these matters (a full citation appears in
788 <a href="file://C|\msysgit\mingw\html/pod/perlfaq2.html">the perlfaq2 manpage</a>).</p>
790 </p>
791 <h2><a name="what_s_wrong_with_using_grep_in_a_void_context_x_grep_">What's wrong with using grep in a void context?
792 </a></h2>
793 <p>The problem is that grep builds a return list, regardless of the context.
794 This means you're making Perl go to the trouble of building a list that
795 you then just throw away. If the list is large, you waste both time and space.
796 If your intent is to iterate over the list, then use a for loop for this
797 purpose.</p>
798 <p>In perls older than 5.8.1, map suffers from this problem as well.
799 But since 5.8.1, this has been fixed, and map is context aware - in void
800 context, no lists are constructed.</p>
802 </p>
803 <h2><a name="how_can_i_match_strings_with_multibyte_characters_x_regex__and_multibyte_characters__x_regexp__and_multibyte_characters__x_regular_expression__and_multibyte_characters_">How can I match strings with multibyte characters?
805 </a></h2>
806 <p>Starting from Perl 5.6 Perl has had some level of multibyte character
807 support. Perl 5.8 or later is recommended. Supported multibyte
808 character repertoires include Unicode, and legacy encodings
809 through the Encode module. See <a href="file://C|\msysgit\mingw\html/pod/perluniintro.html">the perluniintro manpage</a>, <a href="file://C|\msysgit\mingw\html/pod/perlunicode.html">the perlunicode manpage</a>,
810 and <a href="file://C|\msysgit\mingw\html/lib/Encode.html">the Encode manpage</a>.</p>
811 <p>If you are stuck with older Perls, you can do Unicode with the
812 <code>Unicode::String</code> module, and character conversions using the
813 <code>Unicode::Map8</code> and <code>Unicode::Map</code> modules. If you are using
814 Japanese encodings, you might try using the jperl 5.005_03.</p>
815 <p>Finally, the following set of approaches was offered by Jeffrey
816 Friedl, whose article in issue #5 of The Perl Journal talks about
817 this very matter.</p>
818 <p>Let's suppose you have some weird Martian encoding where pairs of
819 ASCII uppercase letters encode single Martian letters (i.e. the two
820 bytes ``CV'' make a single Martian letter, as do the two bytes ``SG'',
821 ``VS'', ``XX'', etc.). Other bytes represent single characters, just like
822 ASCII.</p>
823 <p>So, the string of Martian ``I am CVSGXX!'' uses 12 bytes to encode the
824 nine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.</p>
825 <p>Now, say you want to search for the single character <code>/GX/</code>. Perl
826 doesn't know about Martian, so it'll find the two bytes ``GX'' in the ``I
827 am CVSGXX!'' string, even though that character isn't there: it just
828 looks like it is because ``SG'' is next to ``XX'', but there's no real
829 ``GX''. This is a big problem.</p>
830 <p>Here are a few ways, all painful, to deal with it:</p>
831 <pre>
832 $martian =~ s/([A-Z][A-Z])/ $1 /g; # Make sure adjacent &quot;martian&quot;
833 # bytes are no longer adjacent.
834 print &quot;found GX!\n&quot; if $martian =~ /GX/;</pre>
835 <p>Or like this:</p>
836 <pre>
837 @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;
838 # above is conceptually similar to: @chars = $text =~ m/(.)/g;
840 foreach $char (@chars) {
841 print &quot;found GX!\n&quot;, last if $char eq 'GX';
842 }</pre>
843 <p>Or like this:</p>
844 <pre>
845 while ($martian =~ m/\G([A-Z][A-Z]|.)/gs) { # \G probably unneeded
846 print &quot;found GX!\n&quot;, last if $1 eq 'GX';
847 }</pre>
848 <p>Here's another, slightly less painful, way to do it from Benjamin
849 Goldberg, who uses a zero-width negative look-behind assertion.</p>
850 <pre>
851 print &quot;found GX!\n&quot; if $martian =~ m/
852 (?&lt;![A-Z])
853 (?:[A-Z][A-Z])*?
855 /x;</pre>
856 <p>This succeeds if the ``martian'' character GX is in the string, and fails
857 otherwise. If you don't like using (?&lt;!), a zero-width negative
858 look-behind assertion, you can replace (?&lt;![A-Z]) with (?:^|[^A-Z]).</p>
859 <p>It does have the drawback of putting the wrong thing in $-[0] and $+[0],
860 but this usually can be worked around.</p>
862 </p>
863 <h2><a name="how_do_i_match_a_pattern_that_is_supplied_by_the_user">How do I match a pattern that is supplied by the user?</a></h2>
864 <p>Well, if it's really a pattern, then just use</p>
865 <pre>
866 chomp($pattern = &lt;STDIN&gt;);
867 if ($line =~ /$pattern/) { }</pre>
868 <p>Alternatively, since you have no guarantee that your user entered
869 a valid regular expression, trap the exception this way:</p>
870 <pre>
871 if (eval { $line =~ /$pattern/ }) { }</pre>
872 <p>If all you really want is to search for a string, not a pattern,
873 then you should either use the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_index"><code>index()</code></a> function, which is made for
874 string searching, or, if you can't be disabused of using a pattern
875 match on a non-pattern, then be sure to use <code>\Q</code>...<code>\E</code>, documented
876 in <a href="file://C|\msysgit\mingw\html/pod/perlre.html">the perlre manpage</a>.</p>
877 <pre>
878 $pattern = &lt;STDIN&gt;;</pre>
879 <pre>
880 open (FILE, $input) or die &quot;Couldn't open input $input: $!; aborting&quot;;
881 while (&lt;FILE&gt;) {
882 print if /\Q$pattern\E/;
884 close FILE;</pre>
886 </p>
887 <hr />
888 <h1><a name="author_and_copyright">AUTHOR AND COPYRIGHT</a></h1>
889 <p>Copyright (c) 1997-2006 Tom Christiansen, Nathan Torkington, and
890 other authors as noted. All rights reserved.</p>
891 <p>This documentation is free; you can redistribute it and/or modify it
892 under the same terms as Perl itself.</p>
893 <p>Irrespective of its distribution, all code examples in this file
894 are hereby placed into the public domain. You are permitted and
895 encouraged to use this code in your own programs for fun
896 or for profit as you see fit. A simple comment in the code giving
897 credit would be courteous but is not required.</p>
898 <table border="0" width="100%" cellspacing="0" cellpadding="3">
899 <tr><td class="block" style="background-color: #cccccc" valign="middle">
900 <big><strong><span class="block">&nbsp;perlfaq6 - Regular Expressions</span></strong></big>
901 </td></tr>
902 </table>
904 </body>
906 </html>