Commit | Line | Data |
a0d0e21e |
1 | =head1 NAME |
2 | |
3 | perlre - Perl regular expressions |
4 | |
5 | =head1 DESCRIPTION |
6 | |
cb1a09d0 |
7 | This page describes the syntax of regular expressions in Perl. For a |
5f05dabc |
8 | description of how to I<use> regular expressions in matching |
cb1a09d0 |
9 | operations, plus various examples of the same, see C<m//> and C<s///> in |
10 | L<perlop>. |
11 | |
68dc0745 |
12 | The matching operations can have various modifiers. The modifiers |
13 | which relate to the interpretation of the regular expression inside |
14 | are listed below. For the modifiers that alter the behaviour of the |
15 | operation, see L<perlop/"m//"> and L<perlop/"s//">. |
a0d0e21e |
16 | |
55497cff |
17 | =over 4 |
18 | |
19 | =item i |
20 | |
21 | Do case-insensitive pattern matching. |
22 | |
a034a98d |
23 | If C<use locale> is in effect, the case map is taken from the current |
24 | locale. See L<perllocale>. |
25 | |
54310121 |
26 | =item m |
55497cff |
27 | |
28 | Treat string as multiple lines. That is, change "^" and "$" from matching |
5f05dabc |
29 | at only the very start or end of the string to the start or end of any |
55497cff |
30 | line anywhere within the string, |
31 | |
54310121 |
32 | =item s |
55497cff |
33 | |
34 | Treat string as single line. That is, change "." to match any character |
35 | whatsoever, even a newline, which it normally would not match. |
36 | |
7b8d334a |
37 | The /s and /m modifiers both override the C<$*> setting. That is, no matter |
38 | what C<$*> contains, /s (without /m) will force "^" to match only at the |
39 | beginning of the string and "$" to match only at the end (or just before a |
40 | newline at the end) of the string. Together, as /ms, they let the "." match |
41 | any character whatsoever, while yet allowing "^" and "$" to match, |
42 | respectively, just after and just before newlines within the string. |
43 | |
54310121 |
44 | =item x |
55497cff |
45 | |
46 | Extend your pattern's legibility by permitting whitespace and comments. |
47 | |
48 | =back |
a0d0e21e |
49 | |
50 | These are usually written as "the C</x> modifier", even though the delimiter |
51 | in question might not actually be a slash. In fact, any of these |
52 | modifiers may also be embedded within the regular expression itself using |
53 | the new C<(?...)> construct. See below. |
54 | |
4633a7c4 |
55 | The C</x> modifier itself needs a little more explanation. It tells |
55497cff |
56 | the regular expression parser to ignore whitespace that is neither |
57 | backslashed nor within a character class. You can use this to break up |
4633a7c4 |
58 | your regular expression into (slightly) more readable parts. The C<#> |
54310121 |
59 | character is also treated as a metacharacter introducing a comment, |
55497cff |
60 | just as in ordinary Perl code. This also means that if you want real |
61 | whitespace or C<#> characters in the pattern that you'll have to either |
62 | escape them or encode them using octal or hex escapes. Taken together, |
63 | these features go a long way towards making Perl's regular expressions |
64 | more readable. See the C comment deletion code in L<perlop>. |
a0d0e21e |
65 | |
66 | =head2 Regular Expressions |
67 | |
68 | The patterns used in pattern matching are regular expressions such as |
69 | those supplied in the Version 8 regexp routines. (In fact, the |
70 | routines are derived (distantly) from Henry Spencer's freely |
71 | redistributable reimplementation of the V8 routines.) |
72 | See L<Version 8 Regular Expressions> for details. |
73 | |
74 | In particular the following metacharacters have their standard I<egrep>-ish |
75 | meanings: |
76 | |
54310121 |
77 | \ Quote the next metacharacter |
a0d0e21e |
78 | ^ Match the beginning of the line |
79 | . Match any character (except newline) |
c07a80fd |
80 | $ Match the end of the line (or before newline at the end) |
a0d0e21e |
81 | | Alternation |
82 | () Grouping |
83 | [] Character class |
84 | |
5f05dabc |
85 | By default, the "^" character is guaranteed to match at only the |
86 | beginning of the string, the "$" character at only the end (or before the |
a0d0e21e |
87 | newline at the end) and Perl does certain optimizations with the |
88 | assumption that the string contains only one line. Embedded newlines |
89 | will not be matched by "^" or "$". You may, however, wish to treat a |
4a6725af |
90 | string as a multi-line buffer, such that the "^" will match after any |
a0d0e21e |
91 | newline within the string, and "$" will match before any newline. At the |
92 | cost of a little more overhead, you can do this by using the /m modifier |
93 | on the pattern match operator. (Older programs did this by setting C<$*>, |
5f05dabc |
94 | but this practice is now deprecated.) |
a0d0e21e |
95 | |
4a6725af |
96 | To facilitate multi-line substitutions, the "." character never matches a |
55497cff |
97 | newline unless you use the C</s> modifier, which in effect tells Perl to pretend |
a0d0e21e |
98 | the string is a single line--even if it isn't. The C</s> modifier also |
99 | overrides the setting of C<$*>, in case you have some (badly behaved) older |
100 | code that sets it in another module. |
101 | |
102 | The following standard quantifiers are recognized: |
103 | |
104 | * Match 0 or more times |
105 | + Match 1 or more times |
106 | ? Match 1 or 0 times |
107 | {n} Match exactly n times |
108 | {n,} Match at least n times |
109 | {n,m} Match at least n but not more than m times |
110 | |
111 | (If a curly bracket occurs in any other context, it is treated |
112 | as a regular character.) The "*" modifier is equivalent to C<{0,}>, the "+" |
25f94b33 |
113 | modifier to C<{1,}>, and the "?" modifier to C<{0,1}>. n and m are limited |
c07a80fd |
114 | to integral values less than 65536. |
a0d0e21e |
115 | |
54310121 |
116 | By default, a quantified subpattern is "greedy", that is, it will match as |
117 | many times as possible (given a particular starting location) while still |
118 | allowing the rest of the pattern to match. If you want it to match the |
119 | minimum number of times possible, follow the quantifier with a "?". Note |
120 | that the meanings don't change, just the "greediness": |
a0d0e21e |
121 | |
122 | *? Match 0 or more times |
123 | +? Match 1 or more times |
124 | ?? Match 0 or 1 time |
125 | {n}? Match exactly n times |
126 | {n,}? Match at least n times |
127 | {n,m}? Match at least n but not more than m times |
128 | |
5f05dabc |
129 | Because patterns are processed as double quoted strings, the following |
a0d0e21e |
130 | also work: |
131 | |
0f36ee90 |
132 | \t tab (HT, TAB) |
133 | \n newline (LF, NL) |
134 | \r return (CR) |
135 | \f form feed (FF) |
136 | \a alarm (bell) (BEL) |
137 | \e escape (think troff) (ESC) |
cb1a09d0 |
138 | \033 octal char (think of a PDP-11) |
139 | \x1B hex char |
a0d0e21e |
140 | \c[ control char |
cb1a09d0 |
141 | \l lowercase next char (think vi) |
142 | \u uppercase next char (think vi) |
143 | \L lowercase till \E (think vi) |
144 | \U uppercase till \E (think vi) |
145 | \E end case modification (think vi) |
201ecf35 |
146 | \Q quote (disable) regexp metacharacters till \E |
a0d0e21e |
147 | |
a034a98d |
148 | If C<use locale> is in effect, the case map used by C<\l>, C<\L>, C<\u> |
7b8d334a |
149 | and C<\U> is taken from the current locale. See L<perllocale>. |
a034a98d |
150 | |
a0d0e21e |
151 | In addition, Perl defines the following: |
152 | |
153 | \w Match a "word" character (alphanumeric plus "_") |
154 | \W Match a non-word character |
155 | \s Match a whitespace character |
156 | \S Match a non-whitespace character |
157 | \d Match a digit character |
158 | \D Match a non-digit character |
159 | |
160 | Note that C<\w> matches a single alphanumeric character, not a whole |
a034a98d |
161 | word. To match a word you'd need to say C<\w+>. If C<use locale> is in |
162 | effect, the list of alphabetic characters generated by C<\w> is taken |
163 | from the current locale. See L<perllocale>. You may use C<\w>, C<\W>, |
164 | C<\s>, C<\S>, C<\d>, and C<\D> within character classes (though not as |
165 | either end of a range). |
a0d0e21e |
166 | |
167 | Perl defines the following zero-width assertions: |
168 | |
169 | \b Match a word boundary |
170 | \B Match a non-(word boundary) |
5f05dabc |
171 | \A Match at only beginning of string |
172 | \Z Match at only end of string (or before newline at the end) |
a99df21c |
173 | \G Match only where previous m//g left off (works only with /g) |
a0d0e21e |
174 | |
175 | A word boundary (C<\b>) is defined as a spot between two characters that |
68dc0745 |
176 | has a C<\w> on one side of it and a C<\W> on the other side of it (in |
a0d0e21e |
177 | either order), counting the imaginary characters off the beginning and |
178 | end of the string as matching a C<\W>. (Within character classes C<\b> |
179 | represents backspace rather than a word boundary.) The C<\A> and C<\Z> are |
180 | just like "^" and "$" except that they won't match multiple times when the |
181 | C</m> modifier is used, while "^" and "$" will match at every internal line |
c07a80fd |
182 | boundary. To match the actual end of the string, not ignoring newline, |
a99df21c |
183 | you can use C<\Z(?!\n)>. The C<\G> assertion can be used to chain global |
184 | matches (using C<m//g>), as described in |
e7ea3e70 |
185 | L<perlop/"Regexp Quote-Like Operators">. |
a99df21c |
186 | |
e7ea3e70 |
187 | It is also useful when writing C<lex>-like scanners, when you have several |
188 | regexps which you want to match against consequent substrings of your |
189 | string, see the previous reference. |
44a8e56a |
190 | The actual location where C<\G> will match can also be influenced |
191 | by using C<pos()> as an lvalue. See L<perlfunc/pos>. |
a0d0e21e |
192 | |
0f36ee90 |
193 | When the bracketing construct C<( ... )> is used, \E<lt>digitE<gt> matches the |
cb1a09d0 |
194 | digit'th substring. Outside of the pattern, always use "$" instead of "\" |
0f36ee90 |
195 | in front of the digit. (While the \E<lt>digitE<gt> notation can on rare occasion work |
cb1a09d0 |
196 | outside the current pattern, this should not be relied upon. See the |
0f36ee90 |
197 | WARNING below.) The scope of $E<lt>digitE<gt> (and C<$`>, C<$&>, and C<$'>) |
cb1a09d0 |
198 | extends to the end of the enclosing BLOCK or eval string, or to the next |
199 | successful pattern match, whichever comes first. If you want to use |
5f05dabc |
200 | parentheses to delimit a subpattern (e.g., a set of alternatives) without |
84dc3c4d |
201 | saving it as a subpattern, follow the ( with a ?:. |
cb1a09d0 |
202 | |
203 | You may have as many parentheses as you wish. If you have more |
a0d0e21e |
204 | than 9 substrings, the variables $10, $11, ... refer to the |
205 | corresponding substring. Within the pattern, \10, \11, etc. refer back |
5f05dabc |
206 | to substrings if there have been at least that many left parentheses before |
c07a80fd |
207 | the backreference. Otherwise (for backward compatibility) \10 is the |
a0d0e21e |
208 | same as \010, a backspace, and \11 the same as \011, a tab. And so |
209 | on. (\1 through \9 are always backreferences.) |
210 | |
211 | C<$+> returns whatever the last bracket match matched. C<$&> returns the |
0f36ee90 |
212 | entire matched string. (C<$0> used to return the same thing, but not any |
a0d0e21e |
213 | more.) C<$`> returns everything before the matched string. C<$'> returns |
214 | everything after the matched string. Examples: |
215 | |
216 | s/^([^ ]*) *([^ ]*)/$2 $1/; # swap first two words |
217 | |
218 | if (/Time: (..):(..):(..)/) { |
219 | $hours = $1; |
220 | $minutes = $2; |
221 | $seconds = $3; |
222 | } |
223 | |
68dc0745 |
224 | Once perl sees that you need one of C<$&>, C<$`> or C<$'> anywhere in |
225 | the program, it has to provide them on each and every pattern match. |
226 | This can slow your program down. The same mechanism that handles |
227 | these provides for the use of $1, $2, etc., so you pay the same price |
228 | for each regexp that contains capturing parentheses. But if you never |
229 | use $&, etc., in your script, then regexps I<without> capturing |
230 | parentheses won't be penalized. So avoid $&, $', and $` if you can, |
231 | but if you can't (and some algorithms really appreciate them), once |
232 | you've used them once, use them at will, because you've already paid |
233 | the price. |
234 | |
a0d0e21e |
235 | You will note that all backslashed metacharacters in Perl are |
201ecf35 |
236 | alphanumeric, such as C<\b>, C<\w>, C<\n>. Unlike some other regular |
237 | expression languages, there are no backslashed symbols that aren't |
238 | alphanumeric. So anything that looks like \\, \(, \), \E<lt>, \E<gt>, |
239 | \{, or \} is always interpreted as a literal character, not a |
240 | metacharacter. This was once used in a common idiom to disable or |
241 | quote the special meanings of regular expression metacharacters in a |
242 | string that you want to use for a pattern. Simply quote all the |
a0d0e21e |
243 | non-alphanumeric characters: |
244 | |
245 | $pattern =~ s/(\W)/\\$1/g; |
246 | |
201ecf35 |
247 | Now it is much more common to see either the quotemeta() function or |
7b8d334a |
248 | the C<\Q> escape sequence used to disable all metacharacters' special |
201ecf35 |
249 | meanings like this: |
a0d0e21e |
250 | |
251 | /$unquoted\Q$quoted\E$unquoted/ |
252 | |
5f05dabc |
253 | Perl defines a consistent extension syntax for regular expressions. |
254 | The syntax is a pair of parentheses with a question mark as the first |
255 | thing within the parentheses (this was a syntax error in older |
256 | versions of Perl). The character after the question mark gives the |
257 | function of the extension. Several extensions are already supported: |
a0d0e21e |
258 | |
259 | =over 10 |
260 | |
cc6b7395 |
261 | =item C<(?#text)> |
a0d0e21e |
262 | |
cb1a09d0 |
263 | A comment. The text is ignored. If the C</x> switch is used to enable |
264 | whitespace formatting, a simple C<#> will suffice. |
a0d0e21e |
265 | |
cc6b7395 |
266 | =item C<(?:regexp)> |
a0d0e21e |
267 | |
0f36ee90 |
268 | This groups things like "()" but doesn't make backreferences like "()" does. So |
a0d0e21e |
269 | |
270 | split(/\b(?:a|b|c)\b/) |
271 | |
272 | is like |
273 | |
274 | split(/\b(a|b|c)\b/) |
275 | |
276 | but doesn't spit out extra fields. |
277 | |
cc6b7395 |
278 | =item C<(?=regexp)> |
a0d0e21e |
279 | |
280 | A zero-width positive lookahead assertion. For example, C</\w+(?=\t)/> |
281 | matches a word followed by a tab, without including the tab in C<$&>. |
282 | |
cc6b7395 |
283 | =item C<(?!regexp)> |
a0d0e21e |
284 | |
285 | A zero-width negative lookahead assertion. For example C</foo(?!bar)/> |
286 | matches any occurrence of "foo" that isn't followed by "bar". Note |
287 | however that lookahead and lookbehind are NOT the same thing. You cannot |
7b8d334a |
288 | use this for lookbehind. |
289 | |
290 | If you are looking for a "bar" which isn't preceded by a "foo", C</(?!foo)bar/> |
291 | will not do what you want. That's because the C<(?!foo)> is just saying that |
292 | the next thing cannot be "foo"--and it's not, it's a "bar", so "foobar" will |
293 | match. You would have to do something like C</(?!foo)...bar/> for that. We |
294 | say "like" because there's the case of your "bar" not having three characters |
295 | before it. You could cover that this way: C</(?:(?!foo)...|^.{0,2})bar/>. |
296 | Sometimes it's still easier just to say: |
a0d0e21e |
297 | |
a3cb178b |
298 | if (/bar/ && $` !~ /foo$/) |
a0d0e21e |
299 | |
c277df42 |
300 | For lookbehind see below. |
301 | |
cc6b7395 |
302 | =item C<(?<=regexp)> |
c277df42 |
303 | |
304 | A zero-width positive lookbehind assertion. For example, C</(?=\t)\w+/> |
305 | matches a word following a tab, without including the tab in C<$&>. |
306 | Works only for fixed-width lookbehind. |
307 | |
cc6b7395 |
308 | =item C<(?<!regexp)> |
c277df42 |
309 | |
310 | A zero-width negative lookbehind assertion. For example C</(?<!bar)foo/> |
311 | matches any occurrence of "foo" that isn't following "bar". |
312 | Works only for fixed-width lookbehind. |
313 | |
cc6b7395 |
314 | =item C<(?{ code })> |
c277df42 |
315 | |
316 | Experimental "evaluate any Perl code" zero-width assertion. Always |
cc6b7395 |
317 | succeeds. C<code> is not interpolated. Currently the rules to |
318 | determine where the C<code> ends are somewhat convoluted. |
c277df42 |
319 | |
320 | =item C<(?E<gt>regexp)> |
321 | |
322 | An "independend" subexpression. Matches the substring which a |
323 | I<standalone> C<regexp> would match if anchored at the given position, |
324 | B<and only this substring>. |
325 | |
326 | Say, C<^(?E<gt>a*)ab> will never match, since C<(?E<gt>a*)> (anchored |
327 | at the beginning of string, as above) will match I<all> the characters |
328 | C<a> at the beginning of string, leaving no C<a> for C<ab> to match. |
329 | In contrast, C<a*ab> will match the same as C<a+b>, since the match of |
330 | the subgroup C<a*> is influenced by the following group C<ab> (see |
331 | L<"Backtracking">). In particular, C<a*> inside C<a*ab> will match |
332 | less characters that a standalone C<a*>, since this makes the tail match. |
333 | |
334 | Note that a similar effect to C<(?E<gt>regexp)> may be achieved by |
335 | |
336 | (?=(regexp))\1 |
337 | |
338 | since the lookahead is in I<"logical"> context, thus matches the same |
339 | substring as a standalone C<a+>. The following C<\1> eats the matched |
340 | string, thus making a zero-length assertion into an analogue of |
341 | C<(?>...)>. (The difference of these two constructions is that the |
342 | second one uses a catching group, thus shifts ordinals of |
343 | backreferences in the rest of a regular expression.) |
344 | |
345 | This construction is very useful for optimizations of "eternal" |
346 | matches, since it will not backtrack (see L<"Backtracking">). Say, |
347 | |
348 | / \( ( |
349 | [^()]+ |
350 | | |
351 | \( [^()]* \) |
352 | )+ |
353 | \) /x |
354 | |
355 | will match a nonempty group with matching two-or-less-level-deep |
356 | parentheses. It is very efficient in finding such groups. However, |
357 | if there is no such group, it is going to take forever (on reasonably |
358 | long string), since there are so many different ways to split a long |
359 | string into several substrings (this is essentially what C<(.+)+> is |
360 | doing, and this is a subpattern of the above pattern). Say, on |
361 | C<((()aaaaaaaaaaaaaaaaaa> the above pattern detects no-match in 5sec |
362 | (on kitchentop'96 processor), and each extra letter doubles this time. |
363 | |
364 | However, a tiny modification of this |
365 | |
366 | / \( ( |
367 | (?> [^()]+ ) |
368 | | |
369 | \( [^()]* \) |
370 | )+ |
371 | \) /x |
372 | |
373 | which uses (?>...) matches exactly when the above one does (it is a |
374 | good excercise to check this), but finishes in a fourth of the above |
375 | time on a similar string with 1000000 C<a>s. |
376 | |
377 | Note that on simple groups like the above C<(?> [^()]+ )> a similar |
378 | effect may be achieved by negative lookahead, as in C<[^()]+ (?! [^()] )>. |
379 | This was only 4 times slower on a string with 1000000 C<a>s. |
380 | |
cc6b7395 |
381 | =item C<(?(condition)yes-regexp|no-regexp)> |
c277df42 |
382 | |
cc6b7395 |
383 | =item C<(?(condition)yes-regexp)> |
c277df42 |
384 | |
385 | Conditional expression. C<(condition)> should be either an integer in |
386 | parentheses (which is valid if the corresponding pair of parentheses |
387 | matched), or lookahead/lookbehind/evaluate zero-width assertion. |
388 | |
389 | Say, |
390 | |
391 | / ( \( )? |
392 | [^()]+ |
393 | (?(1) \) )/x |
394 | |
395 | matches a chunk of non-parentheses, possibly included in parentheses |
396 | themselves. |
a0d0e21e |
397 | |
48c036b1 |
398 | =item C<(?imstx)> |
a0d0e21e |
399 | |
400 | One or more embedded pattern-match modifiers. This is particularly |
401 | useful for patterns that are specified in a table somewhere, some of |
402 | which want to be case sensitive, and some of which don't. The case |
5f05dabc |
403 | insensitive ones need to include merely C<(?i)> at the front of the |
a0d0e21e |
404 | pattern. For example: |
405 | |
406 | $pattern = "foobar"; |
c07a80fd |
407 | if ( /$pattern/i ) |
a0d0e21e |
408 | |
409 | # more flexible: |
410 | |
411 | $pattern = "(?i)foobar"; |
c07a80fd |
412 | if ( /$pattern/ ) |
a0d0e21e |
413 | |
c277df42 |
414 | Note that these modifiers are localized inside an enclosing group (if |
415 | any). Say, |
416 | |
417 | ( (?i) blah ) \s+ \1 |
418 | |
419 | (assuming C<x> modifier, and no C<i> modifier outside of this group) |
420 | will match a repeated (I<including the case>!) word C<blah> in any |
421 | case. |
422 | |
a0d0e21e |
423 | =back |
424 | |
425 | The specific choice of question mark for this and the new minimal |
426 | matching construct was because 1) question mark is pretty rare in older |
427 | regular expressions, and 2) whenever you see one, you should stop |
428 | and "question" exactly what is going on. That's psychology... |
429 | |
c07a80fd |
430 | =head2 Backtracking |
431 | |
c277df42 |
432 | A fundamental feature of regular expression matching involves the |
433 | notion called I<backtracking>. which is currently used (when needed) |
434 | by all regular expression quantifiers, namely C<*>, C<*?>, C<+>, |
435 | C<+?>, C<{n,m}>, and C<{n,m}?>. |
c07a80fd |
436 | |
437 | For a regular expression to match, the I<entire> regular expression must |
438 | match, not just part of it. So if the beginning of a pattern containing a |
439 | quantifier succeeds in a way that causes later parts in the pattern to |
440 | fail, the matching engine backs up and recalculates the beginning |
441 | part--that's why it's called backtracking. |
442 | |
443 | Here is an example of backtracking: Let's say you want to find the |
444 | word following "foo" in the string "Food is on the foo table.": |
445 | |
446 | $_ = "Food is on the foo table."; |
447 | if ( /\b(foo)\s+(\w+)/i ) { |
448 | print "$2 follows $1.\n"; |
449 | } |
450 | |
451 | When the match runs, the first part of the regular expression (C<\b(foo)>) |
452 | finds a possible match right at the beginning of the string, and loads up |
453 | $1 with "Foo". However, as soon as the matching engine sees that there's |
454 | no whitespace following the "Foo" that it had saved in $1, it realizes its |
68dc0745 |
455 | mistake and starts over again one character after where it had the |
c07a80fd |
456 | tentative match. This time it goes all the way until the next occurrence |
457 | of "foo". The complete regular expression matches this time, and you get |
458 | the expected output of "table follows foo." |
459 | |
460 | Sometimes minimal matching can help a lot. Imagine you'd like to match |
461 | everything between "foo" and "bar". Initially, you write something |
462 | like this: |
463 | |
464 | $_ = "The food is under the bar in the barn."; |
465 | if ( /foo(.*)bar/ ) { |
466 | print "got <$1>\n"; |
467 | } |
468 | |
469 | Which perhaps unexpectedly yields: |
470 | |
471 | got <d is under the bar in the > |
472 | |
473 | That's because C<.*> was greedy, so you get everything between the |
474 | I<first> "foo" and the I<last> "bar". In this case, it's more effective |
475 | to use minimal matching to make sure you get the text between a "foo" |
476 | and the first "bar" thereafter. |
477 | |
478 | if ( /foo(.*?)bar/ ) { print "got <$1>\n" } |
479 | got <d is under the > |
480 | |
481 | Here's another example: let's say you'd like to match a number at the end |
482 | of a string, and you also want to keep the preceding part the match. |
483 | So you write this: |
484 | |
485 | $_ = "I have 2 numbers: 53147"; |
486 | if ( /(.*)(\d*)/ ) { # Wrong! |
487 | print "Beginning is <$1>, number is <$2>.\n"; |
488 | } |
489 | |
490 | That won't work at all, because C<.*> was greedy and gobbled up the |
491 | whole string. As C<\d*> can match on an empty string the complete |
492 | regular expression matched successfully. |
493 | |
8e1088bc |
494 | Beginning is <I have 2 numbers: 53147>, number is <>. |
c07a80fd |
495 | |
496 | Here are some variants, most of which don't work: |
497 | |
498 | $_ = "I have 2 numbers: 53147"; |
499 | @pats = qw{ |
500 | (.*)(\d*) |
501 | (.*)(\d+) |
502 | (.*?)(\d*) |
503 | (.*?)(\d+) |
504 | (.*)(\d+)$ |
505 | (.*?)(\d+)$ |
506 | (.*)\b(\d+)$ |
507 | (.*\D)(\d+)$ |
508 | }; |
509 | |
510 | for $pat (@pats) { |
511 | printf "%-12s ", $pat; |
512 | if ( /$pat/ ) { |
513 | print "<$1> <$2>\n"; |
514 | } else { |
515 | print "FAIL\n"; |
516 | } |
517 | } |
518 | |
519 | That will print out: |
520 | |
521 | (.*)(\d*) <I have 2 numbers: 53147> <> |
522 | (.*)(\d+) <I have 2 numbers: 5314> <7> |
523 | (.*?)(\d*) <> <> |
524 | (.*?)(\d+) <I have > <2> |
525 | (.*)(\d+)$ <I have 2 numbers: 5314> <7> |
526 | (.*?)(\d+)$ <I have 2 numbers: > <53147> |
527 | (.*)\b(\d+)$ <I have 2 numbers: > <53147> |
528 | (.*\D)(\d+)$ <I have 2 numbers: > <53147> |
529 | |
530 | As you see, this can be a bit tricky. It's important to realize that a |
531 | regular expression is merely a set of assertions that gives a definition |
532 | of success. There may be 0, 1, or several different ways that the |
533 | definition might succeed against a particular string. And if there are |
5f05dabc |
534 | multiple ways it might succeed, you need to understand backtracking to know which variety of success you will achieve. |
c07a80fd |
535 | |
536 | When using lookahead assertions and negations, this can all get even |
54310121 |
537 | tricker. Imagine you'd like to find a sequence of non-digits not |
c07a80fd |
538 | followed by "123". You might try to write that as |
539 | |
540 | $_ = "ABC123"; |
541 | if ( /^\D*(?!123)/ ) { # Wrong! |
542 | print "Yup, no 123 in $_\n"; |
543 | } |
544 | |
545 | But that isn't going to match; at least, not the way you're hoping. It |
546 | claims that there is no 123 in the string. Here's a clearer picture of |
547 | why it that pattern matches, contrary to popular expectations: |
548 | |
549 | $x = 'ABC123' ; |
550 | $y = 'ABC445' ; |
551 | |
552 | print "1: got $1\n" if $x =~ /^(ABC)(?!123)/ ; |
553 | print "2: got $1\n" if $y =~ /^(ABC)(?!123)/ ; |
554 | |
555 | print "3: got $1\n" if $x =~ /^(\D*)(?!123)/ ; |
556 | print "4: got $1\n" if $y =~ /^(\D*)(?!123)/ ; |
557 | |
558 | This prints |
559 | |
560 | 2: got ABC |
561 | 3: got AB |
562 | 4: got ABC |
563 | |
5f05dabc |
564 | You might have expected test 3 to fail because it seems to a more |
c07a80fd |
565 | general purpose version of test 1. The important difference between |
566 | them is that test 3 contains a quantifier (C<\D*>) and so can use |
567 | backtracking, whereas test 1 will not. What's happening is |
568 | that you've asked "Is it true that at the start of $x, following 0 or more |
5f05dabc |
569 | non-digits, you have something that's not 123?" If the pattern matcher had |
c07a80fd |
570 | let C<\D*> expand to "ABC", this would have caused the whole pattern to |
54310121 |
571 | fail. |
c07a80fd |
572 | The search engine will initially match C<\D*> with "ABC". Then it will |
573 | try to match C<(?!123> with "123" which, of course, fails. But because |
574 | a quantifier (C<\D*>) has been used in the regular expression, the |
575 | search engine can backtrack and retry the match differently |
54310121 |
576 | in the hope of matching the complete regular expression. |
c07a80fd |
577 | |
54310121 |
578 | Well now, |
c07a80fd |
579 | the pattern really, I<really> wants to succeed, so it uses the |
5f05dabc |
580 | standard regexp back-off-and-retry and lets C<\D*> expand to just "AB" this |
c07a80fd |
581 | time. Now there's indeed something following "AB" that is not |
582 | "123". It's in fact "C123", which suffices. |
583 | |
584 | We can deal with this by using both an assertion and a negation. We'll |
585 | say that the first part in $1 must be followed by a digit, and in fact, it |
586 | must also be followed by something that's not "123". Remember that the |
587 | lookaheads are zero-width expressions--they only look, but don't consume |
588 | any of the string in their match. So rewriting this way produces what |
589 | you'd expect; that is, case 5 will fail, but case 6 succeeds: |
590 | |
591 | print "5: got $1\n" if $x =~ /^(\D*)(?=\d)(?!123)/ ; |
592 | print "6: got $1\n" if $y =~ /^(\D*)(?=\d)(?!123)/ ; |
593 | |
594 | 6: got ABC |
595 | |
596 | In other words, the two zero-width assertions next to each other work like |
597 | they're ANDed together, just as you'd use any builtin assertions: C</^$/> |
598 | matches only if you're at the beginning of the line AND the end of the |
599 | line simultaneously. The deeper underlying truth is that juxtaposition in |
600 | regular expressions always means AND, except when you write an explicit OR |
601 | using the vertical bar. C</ab/> means match "a" AND (then) match "b", |
602 | although the attempted matches are made at different positions because "a" |
603 | is not a zero-width assertion, but a one-width assertion. |
604 | |
605 | One warning: particularly complicated regular expressions can take |
606 | exponential time to solve due to the immense number of possible ways they |
607 | can use backtracking to try match. For example this will take a very long |
608 | time to run |
609 | |
610 | /((a{0,5}){0,5}){0,5}/ |
611 | |
612 | And if you used C<*>'s instead of limiting it to 0 through 5 matches, then |
613 | it would take literally forever--or until you ran out of stack space. |
614 | |
c277df42 |
615 | A powerful tool for optimizing such beasts is "independent" groups, |
616 | which do not backtrace (see L<C<(?E<gt>regexp)>>). Note also that |
617 | zero-length lookahead/lookbehind assertions will not backtrace to make |
618 | the tail match, since they are in "logical" context: only the fact |
619 | whether they match or not is considered relevant. For an example |
620 | where side-effects of a lookahead I<might> have influenced the |
621 | following match, see L<C<(?E<gt>regexp)>>. |
622 | |
a0d0e21e |
623 | =head2 Version 8 Regular Expressions |
624 | |
625 | In case you're not familiar with the "regular" Version 8 regexp |
626 | routines, here are the pattern-matching rules not described above. |
627 | |
54310121 |
628 | Any single character matches itself, unless it is a I<metacharacter> |
a0d0e21e |
629 | with a special meaning described here or above. You can cause |
630 | characters which normally function as metacharacters to be interpreted |
5f05dabc |
631 | literally by prefixing them with a "\" (e.g., "\." matches a ".", not any |
a0d0e21e |
632 | character; "\\" matches a "\"). A series of characters matches that |
633 | series of characters in the target string, so the pattern C<blurfl> |
634 | would match "blurfl" in the target string. |
635 | |
636 | You can specify a character class, by enclosing a list of characters |
637 | in C<[]>, which will match any one of the characters in the list. If the |
638 | first character after the "[" is "^", the class matches any character not |
639 | in the list. Within a list, the "-" character is used to specify a |
640 | range, so that C<a-z> represents all the characters between "a" and "z", |
84850974 |
641 | inclusive. If you want "-" itself to be a member of a class, put it |
642 | at the start or end of the list, or escape it with a backslash. (The |
643 | following all specify the same class of three characters: C<[-az]>, |
644 | C<[az-]>, and C<[a\-z]>. All are different from C<[a-z]>, which |
645 | specifies a class containing twenty-six characters.) |
a0d0e21e |
646 | |
54310121 |
647 | Characters may be specified using a metacharacter syntax much like that |
a0d0e21e |
648 | used in C: "\n" matches a newline, "\t" a tab, "\r" a carriage return, |
649 | "\f" a form feed, etc. More generally, \I<nnn>, where I<nnn> is a string |
650 | of octal digits, matches the character whose ASCII value is I<nnn>. |
0f36ee90 |
651 | Similarly, \xI<nn>, where I<nn> are hexadecimal digits, matches the |
a0d0e21e |
652 | character whose ASCII value is I<nn>. The expression \cI<x> matches the |
54310121 |
653 | ASCII character control-I<x>. Finally, the "." metacharacter matches any |
a0d0e21e |
654 | character except "\n" (unless you use C</s>). |
655 | |
656 | You can specify a series of alternatives for a pattern using "|" to |
657 | separate them, so that C<fee|fie|foe> will match any of "fee", "fie", |
658 | or "foe" in the target string (as would C<f(e|i|o)e>). Note that the |
659 | first alternative includes everything from the last pattern delimiter |
660 | ("(", "[", or the beginning of the pattern) up to the first "|", and |
661 | the last alternative contains everything from the last "|" to the next |
662 | pattern delimiter. For this reason, it's common practice to include |
663 | alternatives in parentheses, to minimize confusion about where they |
a3cb178b |
664 | start and end. |
665 | |
666 | Note that alternatives are tried from left to right, so the first |
667 | alternative found for which the entire expression matches, is the one that |
668 | is chosen. This means that alternatives are not necessarily greedy. For |
669 | example: when mathing C<foo|foot> against "barefoot", only the "foo" |
670 | part will match, as that is the first alternative tried, and it successfully |
671 | matches the target string. (This might not seem important, but it is |
672 | important when you are capturing matched text using parentheses.) |
673 | |
674 | Also note that "|" is interpreted as a literal within square brackets, |
675 | so if you write C<[fee|fie|foe]> you're really only matching C<[feio|]>. |
a0d0e21e |
676 | |
54310121 |
677 | Within a pattern, you may designate subpatterns for later reference by |
a0d0e21e |
678 | enclosing them in parentheses, and you may refer back to the I<n>th |
54310121 |
679 | subpattern later in the pattern using the metacharacter \I<n>. |
680 | Subpatterns are numbered based on the left to right order of their |
a0d0e21e |
681 | opening parenthesis. Note that a backreference matches whatever |
54310121 |
682 | actually matched the subpattern in the string being examined, not the |
683 | rules for that subpattern. Therefore, C<(0|0x)\d*\s\1\d*> will |
684 | match "0x1234 0x4321",but not "0x1234 01234", because subpattern 1 |
748a9306 |
685 | actually matched "0x", even though the rule C<0|0x> could |
a0d0e21e |
686 | potentially match the leading 0 in the second number. |
cb1a09d0 |
687 | |
688 | =head2 WARNING on \1 vs $1 |
689 | |
690 | Some people get too used to writing things like |
691 | |
692 | $pattern =~ s/(\W)/\\\1/g; |
693 | |
694 | This is grandfathered for the RHS of a substitute to avoid shocking the |
695 | B<sed> addicts, but it's a dirty habit to get into. That's because in |
5f05dabc |
696 | PerlThink, the righthand side of a C<s///> is a double-quoted string. C<\1> in |
cb1a09d0 |
697 | the usual double-quoted string means a control-A. The customary Unix |
698 | meaning of C<\1> is kludged in for C<s///>. However, if you get into the habit |
699 | of doing that, you get yourself into trouble if you then add an C</e> |
700 | modifier. |
701 | |
702 | s/(\d+)/ \1 + 1 /eg; |
703 | |
704 | Or if you try to do |
705 | |
706 | s/(\d+)/\1000/; |
707 | |
708 | You can't disambiguate that by saying C<\{1}000>, whereas you can fix it with |
709 | C<${1}000>. Basically, the operation of interpolation should not be confused |
710 | with the operation of matching a backreference. Certainly they mean two |
711 | different things on the I<left> side of the C<s///>. |
9fa51da4 |
712 | |
713 | =head2 SEE ALSO |
714 | |
9b599b2a |
715 | L<perlop/"Regexp Quote-Like Operators">. |
716 | |
717 | L<perlfunc/pos>. |
718 | |
719 | L<perllocale>. |
720 | |
9fa51da4 |
721 | "Mastering Regular Expressions" (see L<perlbook>) by Jeffrey Friedl. |