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