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