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