Install Perl 5.8.8
[msysgit.git] / mingw / html / pod / perlre.html
blob0ad20abeca7c42f967b1d5640df772daeff7376f
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>perlre - Perl 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;perlre - Perl 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="#regular_expressions">Regular Expressions</a></li>
27 <li><a href="#extended_patterns">Extended Patterns</a></li>
28 <li><a href="#backtracking">Backtracking</a></li>
29 <li><a href="#version_8_regular_expressions">Version 8 Regular Expressions</a></li>
30 <li><a href="#warning_on__1_vs__1">Warning on \1 vs $1</a></li>
31 <li><a href="#repeated_patterns_matching_zerolength_substring">Repeated patterns matching zero-length substring</a></li>
32 <li><a href="#combining_pieces_together">Combining pieces together</a></li>
33 <li><a href="#creating_custom_re_engines">Creating custom RE engines</a></li>
34 </ul>
36 <li><a href="#bugs">BUGS</a></li>
37 <li><a href="#see_also">SEE ALSO</a></li>
38 </ul>
39 <!-- INDEX END -->
41 <hr />
42 <p>
43 </p>
44 <h1><a name="name_x_regular_expression__x_regex__x_regexp_">NAME
45 </a></h1>
46 <p>perlre - Perl regular expressions</p>
47 <p>
48 </p>
49 <hr />
50 <h1><a name="description">DESCRIPTION</a></h1>
51 <p>This page describes the syntax of regular expressions in Perl.</p>
52 <p>If you haven't used regular expressions before, a quick-start
53 introduction is available in <a href="file://C|\msysgit\mingw\html/pod/perlrequick.html">the perlrequick manpage</a>, and a longer tutorial
54 introduction is available in <a href="file://C|\msysgit\mingw\html/pod/perlretut.html">the perlretut manpage</a>.</p>
55 <p>For reference on how regular expressions are used in matching
56 operations, plus various examples of the same, see discussions of
57 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_m_"><code>m//</code></a>, <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_s_"><code>s///</code></a>, <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_qr_"><code>qr//</code></a> and <code>??</code> in <a href="file://C|\msysgit\mingw\html/pod/perlop.html#regexp_quotelike_operators">Regexp Quote-Like Operators in the perlop manpage</a>.</p>
58 <p>Matching operations can have various modifiers. Modifiers
59 that relate to the interpretation of the regular expression inside
60 are listed below. Modifiers that alter the way a regular expression
61 is used by Perl are detailed in <a href="file://C|\msysgit\mingw\html/pod/perlop.html#regexp_quotelike_operators">Regexp Quote-Like Operators in the perlop manpage</a> and
62 <a href="file://C|\msysgit\mingw\html/pod/perlop.html#gory_details_of_parsing_quoted_constructs">Gory details of parsing quoted constructs in the perlop manpage</a>.</p>
63 <dl>
64 <dt><strong><a name="item_i_x_3c_2fi_3e_x_3cregex_2c_case_2dinsensitive_3e_x">i
66 </a></strong>
68 <dd>
69 <p>Do case-insensitive pattern matching.</p>
70 </dd>
71 <dd>
72 <p>If <code>use locale</code> is in effect, the case map is taken from the current
73 locale. See <a href="file://C|\msysgit\mingw\html/pod/perllocale.html">the perllocale manpage</a>.</p>
74 </dd>
75 </li>
76 <dt><strong><a name="item_m_x_3c_2fm_3e_x_3cregex_2c_multiline_3e_x_3cregexp">m
77 </a></strong>
79 <dd>
80 <p>Treat string as multiple lines. That is, change ``^'' and ``$'' from matching
81 the start or end of the string to matching the start or end of any
82 line anywhere within the string.</p>
83 </dd>
84 </li>
85 <dt><strong><a name="item_s_x_3c_2fs_3e_x_3cregex_2c_single_2dline_3e_x_3cre">s
87 </a></strong>
89 <dd>
90 <p>Treat string as single line. That is, change ``.'' to match any character
91 whatsoever, even a newline, which normally it would not match.</p>
92 </dd>
93 <dd>
94 <p>The <code>/s</code> and <code>/m</code> modifiers both override the <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$*</code></a> setting. That
95 is, no matter what <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$*</code></a> contains, <code>/s</code> without <code>/m</code> will force
96 ``^'' to match only at the beginning of the string and ``$'' to match
97 only at the end (or just before a newline at the end) of the string.
98 Together, as /ms, they let the ``.'' match any character whatsoever,
99 while still allowing ``^'' and ``$'' to match, respectively, just after
100 and just before newlines within the string.</p>
101 </dd>
102 </li>
103 <dt><strong><a name="item_x_x_3c_2fx_3e">x
104 </a></strong>
106 <dd>
107 <p>Extend your pattern's legibility by permitting whitespace and comments.</p>
108 </dd>
109 </li>
110 </dl>
111 <p>These are usually written as ``the <code>/x</code> modifier'', even though the delimiter
112 in question might not really be a slash. Any of these
113 modifiers may also be embedded within the regular expression itself using
114 the <code>(?...)</code> construct. See below.</p>
115 <p>The <code>/x</code> modifier itself needs a little more explanation. It tells
116 the regular expression parser to ignore whitespace that is neither
117 backslashed nor within a character class. You can use this to break up
118 your regular expression into (slightly) more readable parts. The <code>#</code>
119 character is also treated as a metacharacter introducing a comment,
120 just as in ordinary Perl code. This also means that if you want real
121 whitespace or <code>#</code> characters in the pattern (outside a character
122 class, where they are unaffected by <code>/x</code>), that you'll either have to
123 escape them or encode them using octal or hex escapes. Taken together,
124 these features go a long way towards making Perl's regular expressions
125 more readable. Note that you have to be careful not to include the
126 pattern delimiter in the comment--perl has no way of knowing you did
127 not intend to close the pattern early. See the C-comment deletion code
128 in <a href="file://C|\msysgit\mingw\html/pod/perlop.html">the perlop manpage</a>.
129 </p>
131 </p>
132 <h2><a name="regular_expressions">Regular Expressions</a></h2>
133 <p>The patterns used in Perl pattern matching derive from supplied in
134 the Version 8 regex routines. (The routines are derived
135 (distantly) from Henry Spencer's freely redistributable reimplementation
136 of the V8 routines.) See <a href="#version_8_regular_expressions">Version 8 Regular Expressions</a> for
137 details.</p>
138 <p>In particular the following metacharacters have their standard <em>egrep</em>-ish
139 meanings:
141 </p>
142 <pre>
143 \ Quote the next metacharacter
144 ^ Match the beginning of the line
145 . Match any character (except newline)
146 $ Match the end of the line (or before newline at the end)
147 | Alternation
148 () Grouping
149 [] Character class</pre>
150 <p>By default, the ``^'' character is guaranteed to match only the
151 beginning of the string, the ``$'' character only the end (or before the
152 newline at the end), and Perl does certain optimizations with the
153 assumption that the string contains only one line. Embedded newlines
154 will not be matched by ``^'' or ``$''. You may, however, wish to treat a
155 string as a multi-line buffer, such that the ``^'' will match after any
156 newline within the string, and ``$'' will match before any newline. At the
157 cost of a little more overhead, you can do this by using the /m modifier
158 on the pattern match operator. (Older programs did this by setting <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$*</code></a>,
159 but this practice is now deprecated.)
160 </p>
161 <p>To simplify multi-line substitutions, the ``.'' character never matches a
162 newline unless you use the <code>/s</code> modifier, which in effect tells Perl to pretend
163 the string is a single line--even if it isn't. The <code>/s</code> modifier also
164 overrides the setting of <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$*</code></a>, in case you have some (badly behaved) older
165 code that sets it in another module.
166 </p>
167 <p>The following standard quantifiers are recognized:
168 </p>
169 <pre>
170 * Match 0 or more times
171 + Match 1 or more times
172 ? Match 1 or 0 times
173 {n} Match exactly n times
174 {n,} Match at least n times
175 {n,m} Match at least n but not more than m times</pre>
176 <p>(If a curly bracket occurs in any other context, it is treated
177 as a regular character. In particular, the lower bound
178 is not optional.) The ``*'' modifier is equivalent to <code>{0,}</code>, the ``+''
179 modifier to <code>{1,}</code>, and the ``?'' modifier to <code>{0,1}</code>. n and m are limited
180 to integral values less than a preset limit defined when perl is built.
181 This is usually 32766 on the most common platforms. The actual limit can
182 be seen in the error message generated by code such as this:</p>
183 <pre>
184 $_ **= $_ , / {$_} / for 2 .. 42;</pre>
185 <p>By default, a quantified subpattern is ``greedy'', that is, it will match as
186 many times as possible (given a particular starting location) while still
187 allowing the rest of the pattern to match. If you want it to match the
188 minimum number of times possible, follow the quantifier with a ``?''. Note
189 that the meanings don't change, just the ``greediness'':
191 </p>
192 <pre>
193 *? Match 0 or more times
194 +? Match 1 or more times
195 ?? Match 0 or 1 time
196 {n}? Match exactly n times
197 {n,}? Match at least n times
198 {n,m}? Match at least n but not more than m times</pre>
199 <p>Because patterns are processed as double quoted strings, the following
200 also work:
202 </p>
203 <pre>
204 \t tab (HT, TAB)
205 \n newline (LF, NL)
206 \r return (CR)
207 \f form feed (FF)
208 \a alarm (bell) (BEL)
209 \e escape (think troff) (ESC)
210 \033 octal char (think of a PDP-11)
211 \x1B hex char
212 \x{263a} wide hex char (Unicode SMILEY)
213 \c[ control char
214 \N{name} named char
215 \l lowercase next char (think vi)
216 \u uppercase next char (think vi)
217 \L lowercase till \E (think vi)
218 \U uppercase till \E (think vi)
219 \E end case modification (think vi)
220 \Q quote (disable) pattern metacharacters till \E</pre>
221 <p>If <code>use locale</code> is in effect, the case map used by <code>\l</code>, <code>\L</code>, <code>\u</code>
222 and <code>\U</code> is taken from the current locale. See <a href="file://C|\msysgit\mingw\html/pod/perllocale.html">the perllocale manpage</a>. For
223 documentation of <code>\N{name}</code>, see <a href="file://C|\msysgit\mingw\html/lib/charnames.html">the charnames manpage</a>.</p>
224 <p>You cannot include a literal <code>$</code> or <code>@</code> within a <code>\Q</code> sequence.
225 An unescaped <code>$</code> or <code>@</code> interpolates the corresponding variable,
226 while escaping will cause the literal string <code>\$</code> to be matched.
227 You'll need to write something like <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_m_"><code>m/\Quser\E\@\Qhost/</code></a>.</p>
228 <p>In addition, Perl defines the following:
231 </p>
232 <pre>
233 \w Match a &quot;word&quot; character (alphanumeric plus &quot;_&quot;)
234 \W Match a non-&quot;word&quot; character
235 \s Match a whitespace character
236 \S Match a non-whitespace character
237 \d Match a digit character
238 \D Match a non-digit character
239 \pP Match P, named property. Use \p{Prop} for longer names.
240 \PP Match non-P
241 \X Match eXtended Unicode &quot;combining character sequence&quot;,
242 equivalent to (?:\PM\pM*)
243 \C Match a single C char (octet) even under Unicode.
244 NOTE: breaks up characters into their UTF-8 bytes,
245 so you may end up with malformed pieces of UTF-8.
246 Unsupported in lookbehind.</pre>
247 <p>A <code>\w</code> matches a single alphanumeric character (an alphabetic
248 character, or a decimal digit) or <code>_</code>, not a whole word. Use <code>\w+</code>
249 to match a string of Perl-identifier characters (which isn't the same
250 as matching an English word). If <code>use locale</code> is in effect, the list
251 of alphabetic characters generated by <code>\w</code> is taken from the current
252 locale. See <a href="file://C|\msysgit\mingw\html/pod/perllocale.html">the perllocale manpage</a>. You may use <code>\w</code>, <code>\W</code>, <code>\s</code>, <code>\S</code>,
253 <code>\d</code>, and <code>\D</code> within character classes, but if you try to use them
254 as endpoints of a range, that's not a range, the ``-'' is understood
255 literally. If Unicode is in effect, <code>\s</code> matches also ``\x{85}'',
256 ``\x{2028}, and ''\x{2029}``, see <a href="file://C|\msysgit\mingw\html/pod/perlunicode.html">the perlunicode manpage</a> for more details about
257 <code>\pP</code>, <code>\PP</code>, and <code>\X</code>, and <a href="file://C|\msysgit\mingw\html/pod/perluniintro.html">the perluniintro manpage</a> about Unicode in general.
258 You can define your own <code>\p</code> and <code>\P</code> properties, see <a href="file://C|\msysgit\mingw\html/pod/perlunicode.html">the perlunicode manpage</a>.
259 </p>
260 <p>The POSIX character class syntax
261 </p>
262 <pre>
263 [:class:]</pre>
264 <p>is also available. The available classes and their backslash
265 equivalents (if available) are as follows:
268 </p>
269 <pre>
270 alpha
271 alnum
272 ascii
273 blank [1]
274 cntrl
275 digit \d
276 graph
277 lower
278 print
279 punct
280 space \s [2]
281 upper
282 word \w [3]
283 xdigit</pre>
284 <dl>
285 <dt><strong><a name="item__5b1_5d">[1]</a></strong>
287 <dd>
288 <p>A GNU extension equivalent to <code>[ \t]</code>, ``all horizontal whitespace''.</p>
289 </dd>
290 </li>
291 <dt><strong><a name="item__5b2_5d">[2]</a></strong>
293 <dd>
294 <p>Not exactly equivalent to <code>\s</code> since the <code>[[:space:]]</code> includes
295 also the (very rare) ``vertical tabulator'', ``\ck'', chr(11).</p>
296 </dd>
297 </li>
298 <dt><strong><a name="item__5b3_5d">[3]</a></strong>
300 <dd>
301 <p>A Perl extension, see above.</p>
302 </dd>
303 </li>
304 </dl>
305 <p>For example use <code>[:upper:]</code> to match all the uppercase characters.
306 Note that the <code>[]</code> are part of the <code>[::]</code> construct, not part of the
307 whole character class. For example:</p>
308 <pre>
309 [01[:alpha:]%]</pre>
310 <p>matches zero, one, any alphabetic character, and the percentage sign.</p>
311 <p>The following equivalences to Unicode \p{} constructs and equivalent
312 backslash character classes (if available), will hold:
313 </p>
314 <pre>
315 [:...:] \p{...} backslash</pre>
316 <pre>
317 alpha IsAlpha
318 alnum IsAlnum
319 ascii IsASCII
320 blank IsSpace
321 cntrl IsCntrl
322 digit IsDigit \d
323 graph IsGraph
324 lower IsLower
325 print IsPrint
326 punct IsPunct
327 space IsSpace
328 IsSpacePerl \s
329 upper IsUpper
330 word IsWord
331 xdigit IsXDigit</pre>
332 <p>For example <code>[:lower:]</code> and <code>\p{IsLower}</code> are equivalent.</p>
333 <p>If the <code>utf8</code> pragma is not used but the <code>locale</code> pragma is, the
334 classes correlate with the usual <code>isalpha(3)</code> interface (except for
335 ``word'' and ``blank'').</p>
336 <p>The assumedly non-obviously named classes are:</p>
337 <dl>
338 <dt><strong><a name="item_cntrl_x_3ccntrl_3e">cntrl
339 </a></strong>
341 <dd>
342 <p>Any control character. Usually characters that don't produce output as
343 such but instead control the terminal somehow: for example newline and
344 backspace are control characters. All characters with <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_ord"><code>ord()</code></a> less than
345 32 are most often classified as control characters (assuming ASCII,
346 the ISO Latin character sets, and Unicode), as is the character with
347 the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_ord"><code>ord()</code></a> value of 127 (<code>DEL</code>).</p>
348 </dd>
349 </li>
350 <dt><strong><a name="item_graph_x_3cgraph_3e">graph
351 </a></strong>
353 <dd>
354 <p>Any alphanumeric or punctuation (special) character.</p>
355 </dd>
356 </li>
357 <dt><strong><a name="item_print_x_3cprint_3e">print
358 </a></strong>
360 <dd>
361 <p>Any alphanumeric or punctuation (special) character or the space character.</p>
362 </dd>
363 </li>
364 <dt><strong><a name="item_punct_x_3cpunct_3e">punct
365 </a></strong>
367 <dd>
368 <p>Any punctuation (special) character.</p>
369 </dd>
370 </li>
371 <dt><strong><a name="item_xdigit_x_3cxdigit_3e">xdigit
372 </a></strong>
374 <dd>
375 <p>Any hexadecimal digit. Though this may feel silly ([0-9A-Fa-f] would
376 work just fine) it is included for completeness.</p>
377 </dd>
378 </li>
379 </dl>
380 <p>You can negate the [::] character classes by prefixing the class name
381 with a '^'. This is a Perl extension. For example:
382 </p>
383 <pre>
384 POSIX traditional Unicode</pre>
385 <pre>
386 [:^digit:] \D \P{IsDigit}
387 [:^space:] \S \P{IsSpace}
388 [:^word:] \W \P{IsWord}</pre>
389 <p>Perl respects the POSIX standard in that POSIX character classes are
390 only supported within a character class. The POSIX character classes
391 [.cc.] and [=cc=] are recognized but <strong>not</strong> supported and trying to
392 use them will cause an error.</p>
393 <p>Perl defines the following zero-width assertions:
397 </p>
398 <pre>
399 \b Match a word boundary
400 \B Match a non-(word boundary)
401 \A Match only at beginning of string
402 \Z Match only at end of string, or before newline at the end
403 \z Match only at end of string
404 \G Match only at pos() (e.g. at the end-of-match position
405 of prior m//g)</pre>
406 <p>A word boundary (<code>\b</code>) is a spot between two characters
407 that has a <code>\w</code> on one side of it and a <code>\W</code> on the other side
408 of it (in either order), counting the imaginary characters off the
409 beginning and end of the string as matching a <code>\W</code>. (Within
410 character classes <code>\b</code> represents backspace rather than a word
411 boundary, just as it normally does in any double-quoted string.)
412 The <code>\A</code> and <code>\Z</code> are just like ``^'' and ``$'', except that they
413 won't match multiple times when the <code>/m</code> modifier is used, while
414 ``^'' and ``$'' will match at every internal line boundary. To match
415 the actual end of the string and not ignore an optional trailing
416 newline, use <code>\z</code>.
417 </p>
418 <p>The <code>\G</code> assertion can be used to chain global matches (using
419 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_m_"><code>m//g</code></a>), as described in <a href="file://C|\msysgit\mingw\html/pod/perlop.html#regexp_quotelike_operators">Regexp Quote-Like Operators in the perlop manpage</a>.
420 It is also useful when writing <code>lex</code>-like scanners, when you have
421 several patterns that you want to match against consequent substrings
422 of your string, see the previous reference. The actual location
423 where <code>\G</code> will match can also be influenced by using <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_pos"><code>pos()</code></a> as
424 an lvalue: see <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_pos">pos in the perlfunc manpage</a>. Currently <code>\G</code> is only fully
425 supported when anchored to the start of the pattern; while it
426 is permitted to use it elsewhere, as in <code>/(?&lt;=\G..)./g</code>, some
427 such uses (<code>/.\G/g</code>, for example) currently cause problems, and
428 it is recommended that you avoid such usage for now.
429 </p>
430 <p>The bracketing construct <code>( ... )</code> creates capture buffers. To
431 refer to the digit'th buffer use \&lt;digit&gt; within the
432 match. Outside the match use ``$'' instead of ``\''. (The
433 \&lt;digit&gt; notation works in certain circumstances outside
434 the match. See the warning below about \1 vs $1 for details.)
435 Referring back to another part of the match is called a
436 <em>backreference</em>.
438 </p>
439 <p>There is no limit to the number of captured substrings that you may
440 use. However Perl also uses \10, \11, etc. as aliases for \010,
441 \011, etc. (Recall that 0 means octal, so \011 is the character at
442 number 9 in your coded character set; which would be the 10th character,
443 a horizontal tab under ASCII.) Perl resolves this
444 ambiguity by interpreting \10 as a backreference only if at least 10
445 left parentheses have opened before it. Likewise \11 is a
446 backreference only if at least 11 left parentheses have opened
447 before it. And so on. \1 through \9 are always interpreted as
448 backreferences.</p>
449 <p>Examples:</p>
450 <pre>
451 s/^([^ ]*) *([^ ]*)/$2 $1/; # swap first two words</pre>
452 <pre>
453 if (/(.)\1/) { # find first doubled char
454 print &quot;'$1' is the first doubled character\n&quot;;
455 }</pre>
456 <pre>
457 if (/Time: (..):(..):(..)/) { # parse out values
458 $hours = $1;
459 $minutes = $2;
460 $seconds = $3;
461 }</pre>
462 <p>Several special variables also refer back to portions of the previous
463 match. <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$+</code></a> returns whatever the last bracket match matched.
464 <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$&amp;</code></a> returns the entire matched string. (At one point <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item__0"><code>$0</code></a> did
465 also, but now it returns the name of the program.) <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$`</code></a> returns
466 everything before the matched string. <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$'</code></a> returns everything
467 after the matched string. And <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___n"><code>$^N</code></a> contains whatever was matched by
468 the most-recently closed group (submatch). <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___n"><code>$^N</code></a> can be used in
469 extended patterns (see below), for example to assign a submatch to a
470 variable.
471 </p>
472 <p>The numbered match variables ($1, $2, $3, etc.) and the related punctuation
473 set (<a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$+</code></a>, <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$&amp;</code></a>, <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$`</code></a>, <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$'</code></a>, and <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___n"><code>$^N</code></a>) are all dynamically scoped
474 until the end of the enclosing block or until the next successful
475 match, whichever comes first. (See <a href="file://C|\msysgit\mingw\html/pod/perlsyn.html#compound_statements">Compound Statements in the perlsyn manpage</a>.)
477 </p>
478 <p><strong>NOTE</strong>: failed matches in Perl do not reset the match variables,
479 which makes it easier to write code that tests for a series of more
480 specific cases and remembers the best match.</p>
481 <p><strong>WARNING</strong>: Once Perl sees that you need one of <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$&amp;</code></a>, <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$`</code></a>, or
482 <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$'</code></a> anywhere in the program, it has to provide them for every
483 pattern match. This may substantially slow your program. Perl
484 uses the same mechanism to produce $1, $2, etc, so you also pay a
485 price for each pattern that contains capturing parentheses. (To
486 avoid this cost while retaining the grouping behaviour, use the
487 extended regular expression <code>(?: ... )</code> instead.) But if you never
488 use <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$&amp;</code></a>, <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$`</code></a> or <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$'</code></a>, then patterns <em>without</em> capturing
489 parentheses will not be penalized. So avoid <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$&amp;</code></a>, <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$'</code></a>, and <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$`</code></a>
490 if you can, but if you can't (and some algorithms really appreciate
491 them), once you've used them once, use them at will, because you've
492 already paid the price. As of 5.005, <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$&amp;</code></a> is not so costly as the
493 other two.
494 </p>
495 <p>Backslashed metacharacters in Perl are alphanumeric, such as <code>\b</code>,
496 <code>\w</code>, <code>\n</code>. Unlike some other regular expression languages, there
497 are no backslashed symbols that aren't alphanumeric. So anything
498 that looks like \\, \(, \), \&lt;, \&gt;, \{, or \} is always
499 interpreted as a literal character, not a metacharacter. This was
500 once used in a common idiom to disable or quote the special meanings
501 of regular expression metacharacters in a string that you want to
502 use for a pattern. Simply quote all non-``word'' characters:</p>
503 <pre>
504 $pattern =~ s/(\W)/\\$1/g;</pre>
505 <p>(If <code>use locale</code> is set, then this depends on the current locale.)
506 Today it is more common to use the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_quotemeta"><code>quotemeta()</code></a> function or the <code>\Q</code>
507 metaquoting escape sequence to disable all metacharacters' special
508 meanings like this:</p>
509 <pre>
510 /$unquoted\Q$quoted\E$unquoted/</pre>
511 <p>Beware that if you put literal backslashes (those not inside
512 interpolated variables) between <code>\Q</code> and <code>\E</code>, double-quotish
513 backslash interpolation may lead to confusing results. If you
514 <em>need</em> to use literal backslashes within <code>\Q...\E</code>,
515 consult <a href="file://C|\msysgit\mingw\html/pod/perlop.html#gory_details_of_parsing_quoted_constructs">Gory details of parsing quoted constructs in the perlop manpage</a>.</p>
517 </p>
518 <h2><a name="extended_patterns">Extended Patterns</a></h2>
519 <p>Perl also defines a consistent extension syntax for features not
520 found in standard tools like <strong>awk</strong> and <strong>lex</strong>. The syntax is a
521 pair of parentheses with a question mark as the first thing within
522 the parentheses. The character after the question mark indicates
523 the extension.</p>
524 <p>The stability of these extensions varies widely. Some have been
525 part of the core language for many years. Others are experimental
526 and may change without warning or be completely removed. Check
527 the documentation on an individual feature to verify its current
528 status.</p>
529 <p>A question mark was chosen for this and for the minimal-matching
530 construct because 1) question marks are rare in older regular
531 expressions, and 2) whenever you see one, you should stop and
532 ``question'' exactly what is going on. That's psychology...</p>
533 <dl>
534 <dt><strong><a name="item__28_3f_23text_29_x_3c_28_3f_23_29_3e"><code>(?#text)</code>
535 </a></strong>
537 <dd>
538 <p>A comment. The text is ignored. If the <code>/x</code> modifier enables
539 whitespace formatting, a simple <code>#</code> will suffice. Note that Perl closes
540 the comment as soon as it sees a <code>)</code>, so there is no way to put a literal
541 <code>)</code> in the comment.</p>
542 </dd>
543 </li>
544 <dt><strong><a name="item__28_3fimsx_2dimsx_29_x_3c_28_3f_29_3e"><code>(?imsx-imsx)</code>
545 </a></strong>
547 <dd>
548 <p>One or more embedded pattern-match modifiers, to be turned on (or
549 turned off, if preceded by <code>-</code>) for the remainder of the pattern or
550 the remainder of the enclosing pattern group (if any). This is
551 particularly useful for dynamic patterns, such as those read in from a
552 configuration file, read in as an argument, are specified in a table
553 somewhere, etc. Consider the case that some of which want to be case
554 sensitive and some do not. The case insensitive ones need to include
555 merely <code>(?i)</code> at the front of the pattern. For example:</p>
556 </dd>
557 <dd>
558 <pre>
559 $pattern = &quot;foobar&quot;;
560 if ( /$pattern/i ) { }</pre>
561 </dd>
562 <dd>
563 <pre>
564 # more flexible:</pre>
565 </dd>
566 <dd>
567 <pre>
568 $pattern = &quot;(?i)foobar&quot;;
569 if ( /$pattern/ ) { }</pre>
570 </dd>
571 <dd>
572 <p>These modifiers are restored at the end of the enclosing group. For example,</p>
573 </dd>
574 <dd>
575 <pre>
576 ( (?i) blah ) \s+ \1</pre>
577 </dd>
578 <dd>
579 <p>will match a repeated (<em>including the case</em>!) word <code>blah</code> in any
580 case, assuming <a href="file://C|\msysgit\mingw\html/pod/perlguts.html#item_x"><code>x</code></a> modifier, and no <code>i</code> modifier outside this
581 group.</p>
582 </dd>
583 </li>
584 <dt><strong><a name="item__28_3f_3apattern_29_x_3c_28_3f_3a_29_3e"><code>(?:pattern)</code>
585 </a></strong>
587 <dt><strong><a name="item__28_3fimsx_2dimsx_3apattern_29"><code>(?imsx-imsx:pattern)</code></a></strong>
589 <dd>
590 <p>This is for clustering, not capturing; it groups subexpressions like
591 ``()'', but doesn't make backreferences as ``()'' does. So</p>
592 </dd>
593 <dd>
594 <pre>
595 @fields = split(/\b(?:a|b|c)\b/)</pre>
596 </dd>
597 <dd>
598 <p>is like</p>
599 </dd>
600 <dd>
601 <pre>
602 @fields = split(/\b(a|b|c)\b/)</pre>
603 </dd>
604 <dd>
605 <p>but doesn't spit out extra fields. It's also cheaper not to capture
606 characters if you don't need to.</p>
607 </dd>
608 <dd>
609 <p>Any letters between <code>?</code> and <code>:</code> act as flags modifiers as with
610 <code>(?imsx-imsx)</code>. For example,</p>
611 </dd>
612 <dd>
613 <pre>
614 /(?s-i:more.*than).*million/i</pre>
615 </dd>
616 <dd>
617 <p>is equivalent to the more verbose</p>
618 </dd>
619 <dd>
620 <pre>
621 /(?:(?s-i)more.*than).*million/i</pre>
622 </dd>
623 </li>
624 <dt><strong><a name="item__28_3f_3dpattern_29_x_3c_28_3f_3d_29_3e_x_3clook_2"><code>(?=pattern)</code>
625 </a></strong>
627 <dd>
628 <p>A zero-width positive look-ahead assertion. For example, <code>/\w+(?=\t)/</code>
629 matches a word followed by a tab, without including the tab in <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$&amp;</code></a>.</p>
630 </dd>
631 </li>
632 <dt><strong><a name="item__28_3f_21pattern_29_x_3c_28_3f_21_29_3e_x_3clook_2"><code>(?!pattern)</code>
633 </a></strong>
635 <dd>
636 <p>A zero-width negative look-ahead assertion. For example <code>/foo(?!bar)/</code>
637 matches any occurrence of ``foo'' that isn't followed by ``bar''. Note
638 however that look-ahead and look-behind are NOT the same thing. You cannot
639 use this for look-behind.</p>
640 </dd>
641 <dd>
642 <p>If you are looking for a ``bar'' that isn't preceded by a ``foo'', <code>/(?!foo)bar/</code>
643 will not do what you want. That's because the <code>(?!foo)</code> is just saying that
644 the next thing cannot be ``foo''--and it's not, it's a ``bar'', so ``foobar'' will
645 match. You would have to do something like <code>/(?!foo)...bar/</code> for that. We
646 say ``like'' because there's the case of your ``bar'' not having three characters
647 before it. You could cover that this way: <code>/(?:(?!foo)...|^.{0,2})bar/</code>.
648 Sometimes it's still easier just to say:</p>
649 </dd>
650 <dd>
651 <pre>
652 if (/bar/ &amp;&amp; $` !~ /foo$/)</pre>
653 </dd>
654 <dd>
655 <p>For look-behind see below.</p>
656 </dd>
657 </li>
658 <dt><strong><a name="item__28_3f_3c_3dpattern_29_x_3c_28_3f_3c_3d_29_3e_x_3c"><code>(?&lt;=pattern)</code>
659 </a></strong>
661 <dd>
662 <p>A zero-width positive look-behind assertion. For example, <code>/(?&lt;=\t)\w+/</code>
663 matches a word that follows a tab, without including the tab in <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$&amp;</code></a>.
664 Works only for fixed-width look-behind.</p>
665 </dd>
666 </li>
667 <dt><strong><a name="item__28_3f_3c_21pattern_29_x_3c_28_3f_3c_21_29_3e_x_3c"><code>(?&lt;!pattern)</code>
668 </a></strong>
670 <dd>
671 <p>A zero-width negative look-behind assertion. For example <code>/(?&lt;!bar)foo/</code>
672 matches any occurrence of ``foo'' that does not follow ``bar''. Works
673 only for fixed-width look-behind.</p>
674 </dd>
675 </li>
676 <dt><strong><a name="item__28_3f_7b_code__7d_29_x_3c_28_3f_7b_7d_29_3e_x_3cr"><code>(?{ code })</code>
677 </a></strong>
679 <dd>
680 <p><strong>WARNING</strong>: This extended regular expression feature is considered
681 highly experimental, and may be changed or deleted without notice.</p>
682 </dd>
683 <dd>
684 <p>This zero-width assertion evaluates any embedded Perl code. It
685 always succeeds, and its <code>code</code> is not interpolated. Currently,
686 the rules to determine where the <code>code</code> ends are somewhat convoluted.</p>
687 </dd>
688 <dd>
689 <p>This feature can be used together with the special variable <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___n"><code>$^N</code></a> to
690 capture the results of submatches in variables without having to keep
691 track of the number of nested parentheses. For example:</p>
692 </dd>
693 <dd>
694 <pre>
695 $_ = &quot;The brown fox jumps over the lazy dog&quot;;
696 /the (\S+)(?{ $color = $^N }) (\S+)(?{ $animal = $^N })/i;
697 print &quot;color = $color, animal = $animal\n&quot;;</pre>
698 </dd>
699 <dd>
700 <p>Inside the <code>(?{...})</code> block, <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___"><code>$_</code></a> refers to the string the regular
701 expression is matching against. You can also use <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_pos"><code>pos()</code></a> to know what is
702 the current position of matching within this string.</p>
703 </dd>
704 <dd>
705 <p>The <code>code</code> is properly scoped in the following sense: If the assertion
706 is backtracked (compare <a href="#backtracking">Backtracking</a>), all changes introduced after
707 <code>local</code>ization are undone, so that</p>
708 </dd>
709 <dd>
710 <pre>
711 $_ = 'a' x 8;
712 m&lt;
713 (?{ $cnt = 0 }) # Initialize $cnt.
717 local $cnt = $cnt + 1; # Update $cnt, backtracking-safe.
720 aaaa
721 (?{ $res = $cnt }) # On success copy to non-localized
722 # location.
723 &gt;x;</pre>
724 </dd>
725 <dd>
726 <p>will set <code>$res = 4</code>. Note that after the match, $cnt returns to the globally
727 introduced value, because the scopes that restrict <code>local</code> operators
728 are unwound.</p>
729 </dd>
730 <dd>
731 <p>This assertion may be used as a <a href="#item__28_3f_28condition_29yes_2dpattern_7cno_2dpattern_"><code>(?(condition)yes-pattern|no-pattern)</code></a>
732 switch. If <em>not</em> used in this way, the result of evaluation of
733 <code>code</code> is put into the special variable <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___r"><code>$^R</code></a>. This happens
734 immediately, so <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___r"><code>$^R</code></a> can be used from other <code>(?{ code })</code> assertions
735 inside the same regular expression.</p>
736 </dd>
737 <dd>
738 <p>The assignment to <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___r"><code>$^R</code></a> above is properly localized, so the old
739 value of <a href="file://C|\msysgit\mingw\html/pod/perlvar.html#item___r"><code>$^R</code></a> is restored if the assertion is backtracked; compare
740 <a href="#backtracking">Backtracking</a>.</p>
741 </dd>
742 <dd>
743 <p>For reasons of security, this construct is forbidden if the regular
744 expression involves run-time interpolation of variables, unless the
745 perilous <code>use re 'eval'</code> pragma has been used (see <a href="file://C|\msysgit\mingw\html/lib/re.html">the re manpage</a>), or the
746 variables contain results of <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_qr_"><code>qr//</code></a> operator (see
747 <a href="file://C|\msysgit\mingw\html/pod/perlop.html#qr_string_imosx">qr/STRING/imosx in the perlop manpage</a>).</p>
748 </dd>
749 <dd>
750 <p>This restriction is because of the wide-spread and remarkably convenient
751 custom of using run-time determined strings as patterns. For example:</p>
752 </dd>
753 <dd>
754 <pre>
755 $re = &lt;&gt;;
756 chomp $re;
757 $string =~ /$re/;</pre>
758 </dd>
759 <dd>
760 <p>Before Perl knew how to execute interpolated code within a pattern,
761 this operation was completely safe from a security point of view,
762 although it could raise an exception from an illegal pattern. If
763 you turn on the <code>use re 'eval'</code>, though, it is no longer secure,
764 so you should only do so if you are also using taint checking.
765 Better yet, use the carefully constrained evaluation within a Safe
766 compartment. See <a href="file://C|\msysgit\mingw\html/pod/perlsec.html">the perlsec manpage</a> for details about both these mechanisms.</p>
767 </dd>
768 </li>
769 <dt><strong><a name="item__28_3f_3f_7b_code__7d_29_x_3c_28_3f_3f_7b_7d_29_3e"><code>(??{ code })</code>
772 </a></strong>
774 <dd>
775 <p><strong>WARNING</strong>: This extended regular expression feature is considered
776 highly experimental, and may be changed or deleted without notice.
777 A simplified version of the syntax may be introduced for commonly
778 used idioms.</p>
779 </dd>
780 <dd>
781 <p>This is a ``postponed'' regular subexpression. The <code>code</code> is evaluated
782 at run time, at the moment this subexpression may match. The result
783 of evaluation is considered as a regular expression and matched as
784 if it were inserted instead of this construct.</p>
785 </dd>
786 <dd>
787 <p>The <code>code</code> is not interpolated. As before, the rules to determine
788 where the <code>code</code> ends are currently somewhat convoluted.</p>
789 </dd>
790 <dd>
791 <p>The following pattern matches a parenthesized group:</p>
792 </dd>
793 <dd>
794 <pre>
795 $re = qr{
798 (?&gt; [^()]+ ) # Non-parens without backtracking
800 (??{ $re }) # Group with matching parens
803 }x;</pre>
804 </dd>
805 </li>
806 <dt><strong><a name="item__28_3f_3epattern_29_x_3cbacktrack_3e_x_3cbacktrack"><code>(?&gt;pattern)</code>
807 </a></strong>
809 <dd>
810 <p><strong>WARNING</strong>: This extended regular expression feature is considered
811 highly experimental, and may be changed or deleted without notice.</p>
812 </dd>
813 <dd>
814 <p>An ``independent'' subexpression, one which matches the substring
815 that a <em>standalone</em> <code>pattern</code> would match if anchored at the given
816 position, and it matches <em>nothing other than this substring</em>. This
817 construct is useful for optimizations of what would otherwise be
818 ``eternal'' matches, because it will not backtrack (see <a href="#backtracking">Backtracking</a>).
819 It may also be useful in places where the ``grab all you can, and do not
820 give anything back'' semantic is desirable.</p>
821 </dd>
822 <dd>
823 <p>For example: <code>^(?&gt;a*)ab</code> will never match, since <code>(?&gt;a*)</code>
824 (anchored at the beginning of string, as above) will match <em>all</em>
825 characters <code>a</code> at the beginning of string, leaving no <code>a</code> for
826 <code>ab</code> to match. In contrast, <code>a*ab</code> will match the same as <code>a+b</code>,
827 since the match of the subgroup <code>a*</code> is influenced by the following
828 group <code>ab</code> (see <a href="#backtracking">Backtracking</a>). In particular, <code>a*</code> inside
829 <code>a*ab</code> will match fewer characters than a standalone <code>a*</code>, since
830 this makes the tail match.</p>
831 </dd>
832 <dd>
833 <p>An effect similar to <code>(?&gt;pattern)</code> may be achieved by writing
834 <code>(?=(pattern))\1</code>. This matches the same substring as a standalone
835 <code>a+</code>, and the following <code>\1</code> eats the matched string; it therefore
836 makes a zero-length assertion into an analogue of <code>(?&gt;...)</code>.
837 (The difference between these two constructs is that the second one
838 uses a capturing group, thus shifting ordinals of backreferences
839 in the rest of a regular expression.)</p>
840 </dd>
841 <dd>
842 <p>Consider this pattern:</p>
843 </dd>
844 <dd>
845 <pre>
846 m{ \(
848 [^()]+ # x+
850 \( [^()]* \)
853 }x</pre>
854 </dd>
855 <dd>
856 <p>That will efficiently match a nonempty group with matching parentheses
857 two levels deep or less. However, if there is no such group, it
858 will take virtually forever on a long string. That's because there
859 are so many different ways to split a long string into several
860 substrings. This is what <code>(.+)+</code> is doing, and <code>(.+)+</code> is similar
861 to a subpattern of the above pattern. Consider how the pattern
862 above detects no-match on <code>((()aaaaaaaaaaaaaaaaaa</code> in several
863 seconds, but that each extra letter doubles this time. This
864 exponential performance will make it appear that your program has
865 hung. However, a tiny change to this pattern</p>
866 </dd>
867 <dd>
868 <pre>
869 m{ \(
871 (?&gt; [^()]+ ) # change x+ above to (?&gt; x+ )
873 \( [^()]* \)
876 }x</pre>
877 </dd>
878 <dd>
879 <p>which uses <code>(?&gt;...)</code> matches exactly when the one above does (verifying
880 this yourself would be a productive exercise), but finishes in a fourth
881 the time when used on a similar string with 1000000 <code>a</code>s. Be aware,
882 however, that this pattern currently triggers a warning message under
883 the <code>use warnings</code> pragma or <strong>-w</strong> switch saying it
884 <code>&quot;matches null string many times in regex&quot;</code>.</p>
885 </dd>
886 <dd>
887 <p>On simple groups, such as the pattern <code>(?&gt; [^()]+ )</code>, a comparable
888 effect may be achieved by negative look-ahead, as in <code>[^()]+ (?! [^()] )</code>.
889 This was only 4 times slower on a string with 1000000 <code>a</code>s.</p>
890 </dd>
891 <dd>
892 <p>The ``grab all you can, and do not give anything back'' semantic is desirable
893 in many situations where on the first sight a simple <code>()*</code> looks like
894 the correct solution. Suppose we parse text with comments being delimited
895 by <code>#</code> followed by some optional (horizontal) whitespace. Contrary to
896 its appearance, <code>#[ \t]*</code> <em>is not</em> the correct subexpression to match
897 the comment delimiter, because it may ``give up'' some whitespace if
898 the remainder of the pattern can be made to match that way. The correct
899 answer is either one of these:</p>
900 </dd>
901 <dd>
902 <pre>
903 (?&gt;#[ \t]*)
904 #[ \t]*(?![ \t])</pre>
905 </dd>
906 <dd>
907 <p>For example, to grab non-empty comments into $1, one should use either
908 one of these:</p>
909 </dd>
910 <dd>
911 <pre>
912 / (?&gt; \# [ \t]* ) ( .+ ) /x;
913 / \# [ \t]* ( [^ \t] .* ) /x;</pre>
914 </dd>
915 <dd>
916 <p>Which one you pick depends on which of these expressions better reflects
917 the above specification of comments.</p>
918 </dd>
919 </li>
920 <dt><strong><a name="item__28_3f_28condition_29yes_2dpattern_7cno_2dpattern_"><code>(?(condition)yes-pattern|no-pattern)</code>
921 </a></strong>
923 <dt><strong><a name="item__28_3f_28condition_29yes_2dpattern_29"><code>(?(condition)yes-pattern)</code></a></strong>
925 <dd>
926 <p><strong>WARNING</strong>: This extended regular expression feature is considered
927 highly experimental, and may be changed or deleted without notice.</p>
928 </dd>
929 <dd>
930 <p>Conditional expression. <code>(condition)</code> should be either an integer in
931 parentheses (which is valid if the corresponding pair of parentheses
932 matched), or look-ahead/look-behind/evaluate zero-width assertion.</p>
933 </dd>
934 <dd>
935 <p>For example:</p>
936 </dd>
937 <dd>
938 <pre>
939 m{ ( \( )?
940 [^()]+
941 (?(1) \) )
942 }x</pre>
943 </dd>
944 <dd>
945 <p>matches a chunk of non-parentheses, possibly included in parentheses
946 themselves.</p>
947 </dd>
948 </li>
949 </dl>
951 </p>
952 <h2><a name="backtracking_x_backtrack__x_backtracking_">Backtracking
953 </a></h2>
954 <p>NOTE: This section presents an abstract approximation of regular
955 expression behavior. For a more rigorous (and complicated) view of
956 the rules involved in selecting a match among possible alternatives,
957 see <a href="#combining_pieces_together">Combining pieces together</a>.</p>
958 <p>A fundamental feature of regular expression matching involves the
959 notion called <em>backtracking</em>, which is currently used (when needed)
960 by all regular expression quantifiers, namely <code>*</code>, <code>*?</code>, <code>+</code>,
961 <code>+?</code>, <code>{n,m}</code>, and <code>{n,m}?</code>. Backtracking is often optimized
962 internally, but the general principle outlined here is valid.</p>
963 <p>For a regular expression to match, the <em>entire</em> regular expression must
964 match, not just part of it. So if the beginning of a pattern containing a
965 quantifier succeeds in a way that causes later parts in the pattern to
966 fail, the matching engine backs up and recalculates the beginning
967 part--that's why it's called backtracking.</p>
968 <p>Here is an example of backtracking: Let's say you want to find the
969 word following ``foo'' in the string ``Food is on the foo table.'':</p>
970 <pre>
971 $_ = &quot;Food is on the foo table.&quot;;
972 if ( /\b(foo)\s+(\w+)/i ) {
973 print &quot;$2 follows $1.\n&quot;;
974 }</pre>
975 <p>When the match runs, the first part of the regular expression (<a href="file://C|\msysgit\mingw\html/pod/perlguts.html#item_b"><code>\b(foo)</code></a>)
976 finds a possible match right at the beginning of the string, and loads up
977 $1 with ``Foo''. However, as soon as the matching engine sees that there's
978 no whitespace following the ``Foo'' that it had saved in $1, it realizes its
979 mistake and starts over again one character after where it had the
980 tentative match. This time it goes all the way until the next occurrence
981 of ``foo''. The complete regular expression matches this time, and you get
982 the expected output of ``table follows foo.''</p>
983 <p>Sometimes minimal matching can help a lot. Imagine you'd like to match
984 everything between ``foo'' and ``bar''. Initially, you write something
985 like this:</p>
986 <pre>
987 $_ = &quot;The food is under the bar in the barn.&quot;;
988 if ( /foo(.*)bar/ ) {
989 print &quot;got &lt;$1&gt;\n&quot;;
990 }</pre>
991 <p>Which perhaps unexpectedly yields:</p>
992 <pre>
993 got &lt;d is under the bar in the &gt;</pre>
994 <p>That's because <code>.*</code> was greedy, so you get everything between the
995 <em>first</em> ``foo'' and the <em>last</em> ``bar''. Here it's more effective
996 to use minimal matching to make sure you get the text between a ``foo''
997 and the first ``bar'' thereafter.</p>
998 <pre>
999 if ( /foo(.*?)bar/ ) { print &quot;got &lt;$1&gt;\n&quot; }
1000 got &lt;d is under the &gt;</pre>
1001 <p>Here's another example: let's say you'd like to match a number at the end
1002 of a string, and you also want to keep the preceding part of the match.
1003 So you write this:</p>
1004 <pre>
1005 $_ = &quot;I have 2 numbers: 53147&quot;;
1006 if ( /(.*)(\d*)/ ) { # Wrong!
1007 print &quot;Beginning is &lt;$1&gt;, number is &lt;$2&gt;.\n&quot;;
1008 }</pre>
1009 <p>That won't work at all, because <code>.*</code> was greedy and gobbled up the
1010 whole string. As <code>\d*</code> can match on an empty string the complete
1011 regular expression matched successfully.</p>
1012 <pre>
1013 Beginning is &lt;I have 2 numbers: 53147&gt;, number is &lt;&gt;.</pre>
1014 <p>Here are some variants, most of which don't work:</p>
1015 <pre>
1016 $_ = &quot;I have 2 numbers: 53147&quot;;
1017 @pats = qw{
1018 (.*)(\d*)
1019 (.*)(\d+)
1020 (.*?)(\d*)
1021 (.*?)(\d+)
1022 (.*)(\d+)$
1023 (.*?)(\d+)$
1024 (.*)\b(\d+)$
1025 (.*\D)(\d+)$
1026 };</pre>
1027 <pre>
1028 for $pat (@pats) {
1029 printf &quot;%-12s &quot;, $pat;
1030 if ( /$pat/ ) {
1031 print &quot;&lt;$1&gt; &lt;$2&gt;\n&quot;;
1032 } else {
1033 print &quot;FAIL\n&quot;;
1035 }</pre>
1036 <p>That will print out:</p>
1037 <pre>
1038 (.*)(\d*) &lt;I have 2 numbers: 53147&gt; &lt;&gt;
1039 (.*)(\d+) &lt;I have 2 numbers: 5314&gt; &lt;7&gt;
1040 (.*?)(\d*) &lt;&gt; &lt;&gt;
1041 (.*?)(\d+) &lt;I have &gt; &lt;2&gt;
1042 (.*)(\d+)$ &lt;I have 2 numbers: 5314&gt; &lt;7&gt;
1043 (.*?)(\d+)$ &lt;I have 2 numbers: &gt; &lt;53147&gt;
1044 (.*)\b(\d+)$ &lt;I have 2 numbers: &gt; &lt;53147&gt;
1045 (.*\D)(\d+)$ &lt;I have 2 numbers: &gt; &lt;53147&gt;</pre>
1046 <p>As you see, this can be a bit tricky. It's important to realize that a
1047 regular expression is merely a set of assertions that gives a definition
1048 of success. There may be 0, 1, or several different ways that the
1049 definition might succeed against a particular string. And if there are
1050 multiple ways it might succeed, you need to understand backtracking to
1051 know which variety of success you will achieve.</p>
1052 <p>When using look-ahead assertions and negations, this can all get even
1053 trickier. Imagine you'd like to find a sequence of non-digits not
1054 followed by ``123''. You might try to write that as</p>
1055 <pre>
1056 $_ = &quot;ABC123&quot;;
1057 if ( /^\D*(?!123)/ ) { # Wrong!
1058 print &quot;Yup, no 123 in $_\n&quot;;
1059 }</pre>
1060 <p>But that isn't going to match; at least, not the way you're hoping. It
1061 claims that there is no 123 in the string. Here's a clearer picture of
1062 why that pattern matches, contrary to popular expectations:</p>
1063 <pre>
1064 $x = 'ABC123';
1065 $y = 'ABC445';</pre>
1066 <pre>
1067 print &quot;1: got $1\n&quot; if $x =~ /^(ABC)(?!123)/;
1068 print &quot;2: got $1\n&quot; if $y =~ /^(ABC)(?!123)/;</pre>
1069 <pre>
1070 print &quot;3: got $1\n&quot; if $x =~ /^(\D*)(?!123)/;
1071 print &quot;4: got $1\n&quot; if $y =~ /^(\D*)(?!123)/;</pre>
1072 <p>This prints</p>
1073 <pre>
1074 2: got ABC
1075 3: got AB
1076 4: got ABC</pre>
1077 <p>You might have expected test 3 to fail because it seems to a more
1078 general purpose version of test 1. The important difference between
1079 them is that test 3 contains a quantifier (<code>\D*</code>) and so can use
1080 backtracking, whereas test 1 will not. What's happening is
1081 that you've asked ``Is it true that at the start of $x, following 0 or more
1082 non-digits, you have something that's not 123?'' If the pattern matcher had
1083 let <code>\D*</code> expand to ``ABC'', this would have caused the whole pattern to
1084 fail.</p>
1085 <p>The search engine will initially match <code>\D*</code> with ``ABC''. Then it will
1086 try to match <code>(?!123</code> with ``123'', which fails. But because
1087 a quantifier (<code>\D*</code>) has been used in the regular expression, the
1088 search engine can backtrack and retry the match differently
1089 in the hope of matching the complete regular expression.</p>
1090 <p>The pattern really, <em>really</em> wants to succeed, so it uses the
1091 standard pattern back-off-and-retry and lets <code>\D*</code> expand to just ``AB'' this
1092 time. Now there's indeed something following ``AB'' that is not
1093 ``123''. It's ``C123'', which suffices.</p>
1094 <p>We can deal with this by using both an assertion and a negation.
1095 We'll say that the first part in $1 must be followed both by a digit
1096 and by something that's not ``123''. Remember that the look-aheads
1097 are zero-width expressions--they only look, but don't consume any
1098 of the string in their match. So rewriting this way produces what
1099 you'd expect; that is, case 5 will fail, but case 6 succeeds:</p>
1100 <pre>
1101 print &quot;5: got $1\n&quot; if $x =~ /^(\D*)(?=\d)(?!123)/;
1102 print &quot;6: got $1\n&quot; if $y =~ /^(\D*)(?=\d)(?!123)/;</pre>
1103 <pre>
1104 6: got ABC</pre>
1105 <p>In other words, the two zero-width assertions next to each other work as though
1106 they're ANDed together, just as you'd use any built-in assertions: <code>/^$/</code>
1107 matches only if you're at the beginning of the line AND the end of the
1108 line simultaneously. The deeper underlying truth is that juxtaposition in
1109 regular expressions always means AND, except when you write an explicit OR
1110 using the vertical bar. <code>/ab/</code> means match ``a'' AND (then) match ``b'',
1111 although the attempted matches are made at different positions because ``a''
1112 is not a zero-width assertion, but a one-width assertion.</p>
1113 <p><strong>WARNING</strong>: particularly complicated regular expressions can take
1114 exponential time to solve because of the immense number of possible
1115 ways they can use backtracking to try match. For example, without
1116 internal optimizations done by the regular expression engine, this will
1117 take a painfully long time to run:</p>
1118 <pre>
1119 'aaaaaaaaaaaa' =~ /((a{0,5}){0,5})*[c]/</pre>
1120 <p>And if you used <code>*</code>'s in the internal groups instead of limiting them
1121 to 0 through 5 matches, then it would take forever--or until you ran
1122 out of stack space. Moreover, these internal optimizations are not
1123 always applicable. For example, if you put <code>{0,5}</code> instead of <code>*</code>
1124 on the external group, no current optimization is applicable, and the
1125 match takes a long time to finish.</p>
1126 <p>A powerful tool for optimizing such beasts is what is known as an
1127 ``independent group'',
1128 which does not backtrack (see <code>&lt; (?&gt;pattern) &gt;</code>). Note also that
1129 zero-length look-ahead/look-behind assertions will not backtrack to make
1130 the tail match, since they are in ``logical'' context: only
1131 whether they match is considered relevant. For an example
1132 where side-effects of look-ahead <em>might</em> have influenced the
1133 following match, see <code>&lt; (?&gt;pattern) &gt;</code>.</p>
1135 </p>
1136 <h2><a name="version_8_regular_expressions_x_regular_expression__version_8__x_regex__version_8__x_regexp__version_8_">Version 8 Regular Expressions
1137 </a></h2>
1138 <p>In case you're not familiar with the ``regular'' Version 8 regex
1139 routines, here are the pattern-matching rules not described above.</p>
1140 <p>Any single character matches itself, unless it is a <em>metacharacter</em>
1141 with a special meaning described here or above. You can cause
1142 characters that normally function as metacharacters to be interpreted
1143 literally by prefixing them with a ``\'' (e.g., ``\.'' matches a ``.'', not any
1144 character; ``\\'' matches a ``\''). A series of characters matches that
1145 series of characters in the target string, so the pattern <code>blurfl</code>
1146 would match ``blurfl'' in the target string.</p>
1147 <p>You can specify a character class, by enclosing a list of characters
1148 in <code>[]</code>, which will match any one character from the list. If the
1149 first character after the ``['' is ``^'', the class matches any character not
1150 in the list. Within a list, the ``-'' character specifies a
1151 range, so that <code>a-z</code> represents all characters between ``a'' and ``z'',
1152 inclusive. If you want either ``-'' or ``]'' itself to be a member of a
1153 class, put it at the start of the list (possibly after a ``^''), or
1154 escape it with a backslash. ``-'' is also taken literally when it is
1155 at the end of the list, just before the closing ``]''. (The
1156 following all specify the same class of three characters: <code>[-az]</code>,
1157 <code>[az-]</code>, and <code>[a\-z]</code>. All are different from <code>[a-z]</code>, which
1158 specifies a class containing twenty-six characters, even on EBCDIC
1159 based coded character sets.) Also, if you try to use the character
1160 classes <code>\w</code>, <code>\W</code>, <code>\s</code>, <code>\S</code>, <code>\d</code>, or <code>\D</code> as endpoints of
1161 a range, that's not a range, the ``-'' is understood literally.</p>
1162 <p>Note also that the whole range idea is rather unportable between
1163 character sets--and even within character sets they may cause results
1164 you probably didn't expect. A sound principle is to use only ranges
1165 that begin from and end at either alphabets of equal case ([a-e],
1166 [A-E]), or digits ([0-9]). Anything else is unsafe. If in doubt,
1167 spell out the character sets in full.</p>
1168 <p>Characters may be specified using a metacharacter syntax much like that
1169 used in C: ``\n'' matches a newline, ``\t'' a tab, ``\r'' a carriage return,
1170 ``\f'' a form feed, etc. More generally, \<em>nnn</em>, where <em>nnn</em> is a string
1171 of octal digits, matches the character whose coded character set value
1172 is <em>nnn</em>. Similarly, \x<em>nn</em>, where <em>nn</em> are hexadecimal digits,
1173 matches the character whose numeric value is <em>nn</em>. The expression \c<em>x</em>
1174 matches the character control-<em>x</em>. Finally, the ``.'' metacharacter
1175 matches any character except ``\n'' (unless you use <code>/s</code>).</p>
1176 <p>You can specify a series of alternatives for a pattern using ``|'' to
1177 separate them, so that <code>fee|fie|foe</code> will match any of ``fee'', ``fie'',
1178 or ``foe'' in the target string (as would <a href="file://C|\msysgit\mingw\html/pod/perlguts.html#item_f"><code>f(e|i|o)e</code></a>). The
1179 first alternative includes everything from the last pattern delimiter
1180 (``('', ``['', or the beginning of the pattern) up to the first ``|'', and
1181 the last alternative contains everything from the last ``|'' to the next
1182 pattern delimiter. That's why it's common practice to include
1183 alternatives in parentheses: to minimize confusion about where they
1184 start and end.</p>
1185 <p>Alternatives are tried from left to right, so the first
1186 alternative found for which the entire expression matches, is the one that
1187 is chosen. This means that alternatives are not necessarily greedy. For
1188 example: when matching <code>foo|foot</code> against ``barefoot'', only the ``foo''
1189 part will match, as that is the first alternative tried, and it successfully
1190 matches the target string. (This might not seem important, but it is
1191 important when you are capturing matched text using parentheses.)</p>
1192 <p>Also remember that ``|'' is interpreted as a literal within square brackets,
1193 so if you write <code>[fee|fie|foe]</code> you're really only matching <code>[feio|]</code>.</p>
1194 <p>Within a pattern, you may designate subpatterns for later reference
1195 by enclosing them in parentheses, and you may refer back to the
1196 <em>n</em>th subpattern later in the pattern using the metacharacter
1197 \<em>n</em>. Subpatterns are numbered based on the left to right order
1198 of their opening parenthesis. A backreference matches whatever
1199 actually matched the subpattern in the string being examined, not
1200 the rules for that subpattern. Therefore, <code>(0|0x)\d*\s\1\d*</code> will
1201 match ``0x1234 0x4321'', but not ``0x1234 01234'', because subpattern
1202 1 matched ``0x'', even though the rule <code>0|0x</code> could potentially match
1203 the leading 0 in the second number.</p>
1205 </p>
1206 <h2><a name="warning_on__1_vs__1">Warning on \1 vs $1</a></h2>
1207 <p>Some people get too used to writing things like:</p>
1208 <pre>
1209 $pattern =~ s/(\W)/\\\1/g;</pre>
1210 <p>This is grandfathered for the RHS of a substitute to avoid shocking the
1211 <strong>sed</strong> addicts, but it's a dirty habit to get into. That's because in
1212 PerlThink, the righthand side of an <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_s_"><code>s///</code></a> is a double-quoted string. <code>\1</code> in
1213 the usual double-quoted string means a control-A. The customary Unix
1214 meaning of <code>\1</code> is kludged in for <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_s_"><code>s///</code></a>. However, if you get into the habit
1215 of doing that, you get yourself into trouble if you then add an <code>/e</code>
1216 modifier.</p>
1217 <pre>
1218 s/(\d+)/ \1 + 1 /eg; # causes warning under -w</pre>
1219 <p>Or if you try to do</p>
1220 <pre>
1221 s/(\d+)/\1000/;</pre>
1222 <p>You can't disambiguate that by saying <code>\{1}000</code>, whereas you can fix it with
1223 <code>${1}000</code>. The operation of interpolation should not be confused
1224 with the operation of matching a backreference. Certainly they mean two
1225 different things on the <em>left</em> side of the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_s_"><code>s///</code></a>.</p>
1227 </p>
1228 <h2><a name="repeated_patterns_matching_zerolength_substring">Repeated patterns matching zero-length substring</a></h2>
1229 <p><strong>WARNING</strong>: Difficult material (and prose) ahead. This section needs a rewrite.</p>
1230 <p>Regular expressions provide a terse and powerful programming language. As
1231 with most other power tools, power comes together with the ability
1232 to wreak havoc.</p>
1233 <p>A common abuse of this power stems from the ability to make infinite
1234 loops using regular expressions, with something as innocuous as:</p>
1235 <pre>
1236 'foo' =~ m{ ( o? )* }x;</pre>
1237 <p>The <code>o?</code> can match at the beginning of <code>'foo'</code>, and since the position
1238 in the string is not moved by the match, <code>o?</code> would match again and again
1239 because of the <code>*</code> modifier. Another common way to create a similar cycle
1240 is with the looping modifier <code>//g</code>:</p>
1241 <pre>
1242 @matches = ( 'foo' =~ m{ o? }xg );</pre>
1243 <p>or</p>
1244 <pre>
1245 print &quot;match: &lt;$&amp;&gt;\n&quot; while 'foo' =~ m{ o? }xg;</pre>
1246 <p>or the loop implied by split().</p>
1247 <p>However, long experience has shown that many programming tasks may
1248 be significantly simplified by using repeated subexpressions that
1249 may match zero-length substrings. Here's a simple example being:</p>
1250 <pre>
1251 @chars = split //, $string; # // is not magic in split
1252 ($whitewashed = $string) =~ s/()/ /g; # parens avoid magic s// /</pre>
1253 <p>Thus Perl allows such constructs, by <em>forcefully breaking
1254 the infinite loop</em>. The rules for this are different for lower-level
1255 loops given by the greedy modifiers <code>*+{}</code>, and for higher-level
1256 ones like the <code>/g</code> modifier or <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_split"><code>split()</code></a> operator.</p>
1257 <p>The lower-level loops are <em>interrupted</em> (that is, the loop is
1258 broken) when Perl detects that a repeated expression matched a
1259 zero-length substring. Thus</p>
1260 <pre>
1261 m{ (?: NON_ZERO_LENGTH | ZERO_LENGTH )* }x;</pre>
1262 <p>is made equivalent to</p>
1263 <pre>
1264 m{ (?: NON_ZERO_LENGTH )*
1266 (?: ZERO_LENGTH )?
1267 }x;</pre>
1268 <p>The higher level-loops preserve an additional state between iterations:
1269 whether the last match was zero-length. To break the loop, the following
1270 match after a zero-length match is prohibited to have a length of zero.
1271 This prohibition interacts with backtracking (see <a href="#backtracking">Backtracking</a>),
1272 and so the <em>second best</em> match is chosen if the <em>best</em> match is of
1273 zero length.</p>
1274 <p>For example:</p>
1275 <pre>
1276 $_ = 'bar';
1277 s/\w??/&lt;$&amp;&gt;/g;</pre>
1278 <p>results in <code>&lt;&gt;&lt;b&gt;&lt;&gt;&lt;a&gt;&lt;&gt;&lt;r&gt;&lt;&gt;</code>. At each position of the string the best
1279 match given by non-greedy <code>??</code> is the zero-length match, and the <em>second
1280 best</em> match is what is matched by <code>\w</code>. Thus zero-length matches
1281 alternate with one-character-long matches.</p>
1282 <p>Similarly, for repeated <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_m_"><code>m/()/g</code></a> the second-best match is the match at the
1283 position one notch further in the string.</p>
1284 <p>The additional state of being <em>matched with zero-length</em> is associated with
1285 the matched string, and is reset by each assignment to pos().
1286 Zero-length matches at the end of the previous match are ignored
1287 during <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_split"><code>split</code></a>.</p>
1289 </p>
1290 <h2><a name="combining_pieces_together">Combining pieces together</a></h2>
1291 <p>Each of the elementary pieces of regular expressions which were described
1292 before (such as <code>ab</code> or <code>\Z</code>) could match at most one substring
1293 at the given position of the input string. However, in a typical regular
1294 expression these elementary pieces are combined into more complicated
1295 patterns using combining operators <a href="#item_st"><code>ST</code></a>, <a href="#item_s_7ct"><code>S|T</code></a>, <code>S*</code> etc
1296 (in these examples <a href="#item_s"><code>S</code></a> and <code>T</code> are regular subexpressions).</p>
1297 <p>Such combinations can include alternatives, leading to a problem of choice:
1298 if we match a regular expression <code>a|ab</code> against <code>&quot;abc&quot;</code>, will it match
1299 substring <code>&quot;a&quot;</code> or <code>&quot;ab&quot;</code>? One way to describe which substring is
1300 actually matched is the concept of backtracking (see <a href="#backtracking">Backtracking</a>).
1301 However, this description is too low-level and makes you think
1302 in terms of a particular implementation.</p>
1303 <p>Another description starts with notions of ``better''/``worse''. All the
1304 substrings which may be matched by the given regular expression can be
1305 sorted from the ``best'' match to the ``worst'' match, and it is the ``best''
1306 match which is chosen. This substitutes the question of ``what is chosen?''
1307 by the question of ``which matches are better, and which are worse?''.</p>
1308 <p>Again, for elementary pieces there is no such question, since at most
1309 one match at a given position is possible. This section describes the
1310 notion of better/worse for combining operators. In the description
1311 below <a href="#item_s"><code>S</code></a> and <code>T</code> are regular subexpressions.</p>
1312 <dl>
1313 <dt><strong><a name="item_st"><code>ST</code></a></strong>
1315 <dd>
1316 <p>Consider two possible matches, <code>AB</code> and <code>A'B'</code>, <a href="file://C|\msysgit\mingw\html/pod/perlguts.html#item_a"><code>A</code></a> and <code>A'</code> are
1317 substrings which can be matched by <a href="#item_s"><code>S</code></a>, <code>B</code> and <code>B'</code> are substrings
1318 which can be matched by <code>T</code>.</p>
1319 </dd>
1320 <dd>
1321 <p>If <a href="file://C|\msysgit\mingw\html/pod/perlguts.html#item_a"><code>A</code></a> is better match for <a href="#item_s"><code>S</code></a> than <code>A'</code>, <code>AB</code> is a better
1322 match than <code>A'B'</code>.</p>
1323 </dd>
1324 <dd>
1325 <p>If <a href="file://C|\msysgit\mingw\html/pod/perlguts.html#item_a"><code>A</code></a> and <code>A'</code> coincide: <code>AB</code> is a better match than <code>AB'</code> if
1326 <code>B</code> is better match for <code>T</code> than <code>B'</code>.</p>
1327 </dd>
1328 </li>
1329 <dt><strong><a name="item_s_7ct"><code>S|T</code></a></strong>
1331 <dd>
1332 <p>When <a href="#item_s"><code>S</code></a> can match, it is a better match than when only <code>T</code> can match.</p>
1333 </dd>
1334 <dd>
1335 <p>Ordering of two matches for <a href="#item_s"><code>S</code></a> is the same as for <a href="#item_s"><code>S</code></a>. Similar for
1336 two matches for <code>T</code>.</p>
1337 </dd>
1338 </li>
1339 <dt><strong><a name="item_s"><code>S{REPEAT_COUNT}</code></a></strong>
1341 <dd>
1342 <p>Matches as <code>SSS...S</code> (repeated as many times as necessary).</p>
1343 </dd>
1344 </li>
1345 <dt><strong><code>S{min,max}</code></strong>
1347 <dd>
1348 <p>Matches as <a href="#item_s"><code>S{max}|S{max-1}|...|S{min+1}|S{min}</code></a>.</p>
1349 </dd>
1350 </li>
1351 <dt><strong><a name="item_s_7bmin_2cmax_7d_3f"><code>S{min,max}?</code></a></strong>
1353 <dd>
1354 <p>Matches as <a href="#item_s"><code>S{min}|S{min+1}|...|S{max-1}|S{max}</code></a>.</p>
1355 </dd>
1356 </li>
1357 <dt><strong><a name="item_s_3f_2c_s_2a_2c_s_2b"><code>S?</code>, <code>S*</code>, <code>S+</code></a></strong>
1359 <dd>
1360 <p>Same as <a href="#item_s"><code>S{0,1}</code></a>, <a href="#item_s"><code>S{0,BIG_NUMBER}</code></a>, <a href="#item_s"><code>S{1,BIG_NUMBER}</code></a> respectively.</p>
1361 </dd>
1362 </li>
1363 <dt><strong><a name="item_s_3f_3f_2c_s_2a_3f_2c_s_2b_3f"><code>S??</code>, <code>S*?</code>, <code>S+?</code></a></strong>
1365 <dd>
1366 <p>Same as <code>S{0,1}?</code>, <code>S{0,BIG_NUMBER}?</code>, <code>S{1,BIG_NUMBER}?</code> respectively.</p>
1367 </dd>
1368 </li>
1369 <dt><strong><a name="item__28_3f_3es_29"><code>(?&gt;S)</code></a></strong>
1371 <dd>
1372 <p>Matches the best match for <a href="#item_s"><code>S</code></a> and only that.</p>
1373 </dd>
1374 </li>
1375 <dt><strong><a name="item__28_3f_3ds_29_2c__28_3f_3c_3ds_29"><code>(?=S)</code>, <code>(?&lt;=S)</code></a></strong>
1377 <dd>
1378 <p>Only the best match for <a href="#item_s"><code>S</code></a> is considered. (This is important only if
1379 <a href="#item_s"><code>S</code></a> has capturing parentheses, and backreferences are used somewhere
1380 else in the whole regular expression.)</p>
1381 </dd>
1382 </li>
1383 <dt><strong><a name="item__28_3f_21s_29_2c__28_3f_3c_21s_29"><code>(?!S)</code>, <code>(?&lt;!S)</code></a></strong>
1385 <dd>
1386 <p>For this grouping operator there is no need to describe the ordering, since
1387 only whether or not <a href="#item_s"><code>S</code></a> can match is important.</p>
1388 </dd>
1389 </li>
1390 <dt><strong><a name="item__28_3f_3f_7b_expr__7d_29"><code>(??{ EXPR })</code></a></strong>
1392 <dd>
1393 <p>The ordering is the same as for the regular expression which is
1394 the result of EXPR.</p>
1395 </dd>
1396 </li>
1397 <dt><strong><code>(?(condition)yes-pattern|no-pattern)</code></strong>
1399 <dd>
1400 <p>Recall that which of <code>yes-pattern</code> or <code>no-pattern</code> actually matches is
1401 already determined. The ordering of the matches is the same as for the
1402 chosen subexpression.</p>
1403 </dd>
1404 </li>
1405 </dl>
1406 <p>The above recipes describe the ordering of matches <em>at a given position</em>.
1407 One more rule is needed to understand how a match is determined for the
1408 whole regular expression: a match at an earlier position is always better
1409 than a match at a later position.</p>
1411 </p>
1412 <h2><a name="creating_custom_re_engines">Creating custom RE engines</a></h2>
1413 <p>Overloaded constants (see <a href="file://C|\msysgit\mingw\html/lib/overload.html">the overload manpage</a>) provide a simple way to extend
1414 the functionality of the RE engine.</p>
1415 <p>Suppose that we want to enable a new RE escape-sequence <code>\Y|</code> which
1416 matches at boundary between whitespace characters and non-whitespace
1417 characters. Note that <code>(?=\S)(?&lt;!\S)|(?!\S)(?&lt;=\S)</code> matches exactly
1418 at these positions, so we want to have each <code>\Y|</code> in the place of the
1419 more complicated version. We can create a module <code>customre</code> to do
1420 this:</p>
1421 <pre>
1422 package customre;
1423 use overload;</pre>
1424 <pre>
1425 sub import {
1426 shift;
1427 die &quot;No argument to customre::import allowed&quot; if @_;
1428 overload::constant 'qr' =&gt; \&amp;convert;
1429 }</pre>
1430 <pre>
1431 sub invalid { die &quot;/$_[0]/: invalid escape '\\$_[1]'&quot;}</pre>
1432 <pre>
1433 # We must also take care of not escaping the legitimate \\Y|
1434 # sequence, hence the presence of '\\' in the conversion rules.
1435 my %rules = ( '\\' =&gt; '\\\\',
1436 'Y|' =&gt; qr/(?=\S)(?&lt;!\S)|(?!\S)(?&lt;=\S)/ );
1437 sub convert {
1438 my $re = shift;
1439 $re =~ s{
1440 \\ ( \\ | Y . )
1442 { $rules{$1} or invalid($re,$1) }sgex;
1443 return $re;
1444 }</pre>
1445 <p>Now <code>use customre</code> enables the new escape in constant regular
1446 expressions, i.e., those without any runtime variable interpolations.
1447 As documented in <a href="file://C|\msysgit\mingw\html/lib/overload.html">the overload manpage</a>, this conversion will work only over
1448 literal parts of regular expressions. For <code>\Y|$re\Y|</code> the variable
1449 part of this regular expression needs to be converted explicitly
1450 (but only if the special meaning of <code>\Y|</code> should be enabled inside $re):</p>
1451 <pre>
1452 use customre;
1453 $re = &lt;&gt;;
1454 chomp $re;
1455 $re = customre::convert $re;
1456 /\Y|$re\Y|/;</pre>
1458 </p>
1459 <hr />
1460 <h1><a name="bugs">BUGS</a></h1>
1461 <p>This document varies from difficult to understand to completely
1462 and utterly opaque. The wandering prose riddled with jargon is
1463 hard to fathom in several places.</p>
1464 <p>This document needs a rewrite that separates the tutorial content
1465 from the reference content.</p>
1467 </p>
1468 <hr />
1469 <h1><a name="see_also">SEE ALSO</a></h1>
1470 <p><a href="file://C|\msysgit\mingw\html/pod/perlrequick.html">the perlrequick manpage</a>.</p>
1471 <p><a href="file://C|\msysgit\mingw\html/pod/perlretut.html">the perlretut manpage</a>.</p>
1472 <p><a href="file://C|\msysgit\mingw\html/pod/perlop.html#regexp_quotelike_operators">Regexp Quote-Like Operators in the perlop manpage</a>.</p>
1473 <p><a href="file://C|\msysgit\mingw\html/pod/perlop.html#gory_details_of_parsing_quoted_constructs">Gory details of parsing quoted constructs in the perlop manpage</a>.</p>
1474 <p><a href="file://C|\msysgit\mingw\html/pod/perlfaq6.html">the perlfaq6 manpage</a>.</p>
1475 <p><a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_pos">pos in the perlfunc manpage</a>.</p>
1476 <p><a href="file://C|\msysgit\mingw\html/pod/perllocale.html">the perllocale manpage</a>.</p>
1477 <p><a href="file://C|\msysgit\mingw\html/pod/perlebcdic.html">the perlebcdic manpage</a>.</p>
1478 <p><em>Mastering Regular Expressions</em> by Jeffrey Friedl, published
1479 by O'Reilly and Associates.</p>
1480 <table border="0" width="100%" cellspacing="0" cellpadding="3">
1481 <tr><td class="block" style="background-color: #cccccc" valign="middle">
1482 <big><strong><span class="block">&nbsp;perlre - Perl regular expressions</span></strong></big>
1483 </td></tr>
1484 </table>
1486 </body>
1488 </html>