/
perlre.pod
1800 lines (1372 loc) · 66 KB
/
perlre.pod
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=head1 NAME
X<regular expression> X<regex> X<regexp>
perlre - Perl regular expressions
=head1 DESCRIPTION
This page describes the syntax of regular expressions in Perl.
If you haven't used regular expressions before, a quick-start
introduction is available in L<perlrequick>, and a longer tutorial
introduction is available in L<perlretut>.
For reference on how regular expressions are used in matching
operations, plus various examples of the same, see discussions of
C<m//>, C<s///>, C<qr//> and C<??> in L<perlop/"Regexp Quote-Like
Operators">.
Matching operations can have various modifiers. Modifiers
that relate to the interpretation of the regular expression inside
are listed below. Modifiers that alter the way a regular expression
is used by Perl are detailed in L<perlop/"Regexp Quote-Like Operators"> and
L<perlop/"Gory details of parsing quoted constructs">.
=over 4
=item i
X</i> X<regex, case-insensitive> X<regexp, case-insensitive>
X<regular expression, case-insensitive>
Do case-insensitive pattern matching.
If C<use locale> is in effect, the case map is taken from the current
locale. See L<perllocale>.
=item m
X</m> X<regex, multiline> X<regexp, multiline> X<regular expression, multiline>
Treat string as multiple lines. That is, change "^" and "$" from matching
the start or end of the string to matching the start or end of any
line anywhere within the string.
=item s
X</s> X<regex, single-line> X<regexp, single-line>
X<regular expression, single-line>
Treat string as single line. That is, change "." to match any character
whatsoever, even a newline, which normally it would not match.
Used together, as /ms, they let the "." match any character whatsoever,
while still allowing "^" and "$" to match, respectively, just after
and just before newlines within the string.
=item x
X</x>
Extend your pattern's legibility by permitting whitespace and comments.
=back
These are usually written as "the C</x> modifier", even though the delimiter
in question might not really be a slash. Any of these
modifiers may also be embedded within the regular expression itself using
the C<(?...)> construct. See below.
The C</x> modifier itself needs a little more explanation. It tells
the regular expression parser to ignore whitespace that is neither
backslashed nor within a character class. You can use this to break up
your regular expression into (slightly) more readable parts. The C<#>
character is also treated as a metacharacter introducing a comment,
just as in ordinary Perl code. This also means that if you want real
whitespace or C<#> characters in the pattern (outside a character
class, where they are unaffected by C</x>), then you'll either have to
escape them (using backslashes or C<\Q...\E>) or encode them using octal
or hex escapes. Taken together, these features go a long way towards
making Perl's regular expressions more readable. Note that you have to
be careful not to include the pattern delimiter in the comment--perl has
no way of knowing you did not intend to close the pattern early. See
the C-comment deletion code in L<perlop>. Also note that anything inside
a C<\Q...\E> stays unaffected by C</x>.
X</x>
=head2 Regular Expressions
=head3 Metacharacters
The patterns used in Perl pattern matching derive from supplied in
the Version 8 regex routines. (The routines are derived
(distantly) from Henry Spencer's freely redistributable reimplementation
of the V8 routines.) See L<Version 8 Regular Expressions> for
details.
In particular the following metacharacters have their standard I<egrep>-ish
meanings:
X<metacharacter>
X<\> X<^> X<.> X<$> X<|> X<(> X<()> X<[> X<[]>
\ Quote the next metacharacter
^ Match the beginning of the line
. Match any character (except newline)
$ Match the end of the line (or before newline at the end)
| Alternation
() Grouping
[] Character class
By default, the "^" character is guaranteed to match only the
beginning of the string, the "$" character only the end (or before the
newline at the end), and Perl does certain optimizations with the
assumption that the string contains only one line. Embedded newlines
will not be matched by "^" or "$". You may, however, wish to treat a
string as a multi-line buffer, such that the "^" will match after any
newline within the string, and "$" will match before any newline. At the
cost of a little more overhead, you can do this by using the /m modifier
on the pattern match operator. (Older programs did this by setting C<$*>,
but this practice has been removed in perl 5.9.)
X<^> X<$> X</m>
To simplify multi-line substitutions, the "." character never matches a
newline unless you use the C</s> modifier, which in effect tells Perl to pretend
the string is a single line--even if it isn't.
X<.> X</s>
=head3 Quantifiers
The following standard quantifiers are recognized:
X<metacharacter> X<quantifier> X<*> X<+> X<?> X<{n}> X<{n,}> X<{n,m}>
* Match 0 or more times
+ Match 1 or more times
? Match 1 or 0 times
{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times
(If a curly bracket occurs in any other context, it is treated
as a regular character. In particular, the lower bound
is not optional.) The "*" modifier is equivalent to C<{0,}>, the "+"
modifier to C<{1,}>, and the "?" modifier to C<{0,1}>. n and m are limited
to integral values less than a preset limit defined when perl is built.
This is usually 32766 on the most common platforms. The actual limit can
be seen in the error message generated by code such as this:
$_ **= $_ , / {$_} / for 2 .. 42;
By default, a quantified subpattern is "greedy", that is, it will match as
many times as possible (given a particular starting location) while still
allowing the rest of the pattern to match. If you want it to match the
minimum number of times possible, follow the quantifier with a "?". Note
that the meanings don't change, just the "greediness":
X<metacharacter> X<greedy> X<greedyness>
X<?> X<*?> X<+?> X<??> X<{n}?> X<{n,}?> X<{n,m}?>
*? Match 0 or more times
+? Match 1 or more times
?? Match 0 or 1 time
{n}? Match exactly n times
{n,}? Match at least n times
{n,m}? Match at least n but not more than m times
By default, when a quantified subpattern does not allow the rest of the
overall pattern to match, Perl will backtrack. However, this behaviour is
sometimes undesirable. Thus Perl provides the "possesive" quantifier form
as well.
*+ Match 0 or more times and give nothing back
++ Match 1 or more times and give nothing back
?+ Match 0 or 1 time and give nothing back
{n}+ Match exactly n times and give nothing back (redundant)
{n,}+ Match at least n times and give nothing back
{n,m}+ Match at least n but not more than m times and give nothing back
For instance,
'aaaa' =~ /a++a/
will never match, as the C<a++> will gobble up all the C<a>'s in the
string and won't leave any for the remaining part of the pattern. This
feature can be extremely useful to give perl hints about where it
shouldn't backtrack. For instance, the typical "match a double-quoted
string" problem can be most efficiently performed when written as:
/"(?:[^"\\]++|\\.)*+"/
as we know that if the final quote does not match, bactracking will not
help. See the independent subexpression C<< (?>...) >> for more details;
possessive quantifiers are just syntactic sugar for that construct. For
instance the above example could also be written as follows:
/"(?>(?:(?>[^"\\]+)|\\.)*)"/
=head3 Escape sequences
Because patterns are processed as double quoted strings, the following
also work:
X<\t> X<\n> X<\r> X<\f> X<\a> X<\l> X<\u> X<\L> X<\U> X<\E> X<\Q>
X<\0> X<\c> X<\N> X<\x>
\t tab (HT, TAB)
\n newline (LF, NL)
\r return (CR)
\f form feed (FF)
\a alarm (bell) (BEL)
\e escape (think troff) (ESC)
\033 octal char (think of a PDP-11)
\x1B hex char
\x{263a} wide hex char (Unicode SMILEY)
\c[ control char
\N{name} named char
\l lowercase next char (think vi)
\u uppercase next char (think vi)
\L lowercase till \E (think vi)
\U uppercase till \E (think vi)
\E end case modification (think vi)
\Q quote (disable) pattern metacharacters till \E
If C<use locale> is in effect, the case map used by C<\l>, C<\L>, C<\u>
and C<\U> is taken from the current locale. See L<perllocale>. For
documentation of C<\N{name}>, see L<charnames>.
You cannot include a literal C<$> or C<@> within a C<\Q> sequence.
An unescaped C<$> or C<@> interpolates the corresponding variable,
while escaping will cause the literal string C<\$> to be matched.
You'll need to write something like C<m/\Quser\E\@\Qhost/>.
=head3 Character classes
In addition, Perl defines the following:
X<metacharacter>
X<\w> X<\W> X<\s> X<\S> X<\d> X<\D> X<\X> X<\p> X<\P> X<\C>
X<word> X<whitespace>
\w Match a "word" character (alphanumeric plus "_")
\W Match a non-"word" character
\s Match a whitespace character
\S Match a non-whitespace character
\d Match a digit character
\D Match a non-digit character
\pP Match P, named property. Use \p{Prop} for longer names.
\PP Match non-P
\X Match eXtended Unicode "combining character sequence",
equivalent to (?:\PM\pM*)
\C Match a single C char (octet) even under Unicode.
NOTE: breaks up characters into their UTF-8 bytes,
so you may end up with malformed pieces of UTF-8.
Unsupported in lookbehind.
\1 Backreference to a a specific group.
'1' may actually be any positive integer
\k<name> Named backreference
\N{name} Named unicode character, or unicode escape.
\x12 Hexadecimal escape sequence
\x{1234} Long hexadecimal escape sequence
A C<\w> matches a single alphanumeric character (an alphabetic
character, or a decimal digit) or C<_>, not a whole word. Use C<\w+>
to match a string of Perl-identifier characters (which isn't the same
as matching an English word). If C<use locale> is in effect, the list
of alphabetic characters generated by C<\w> is taken from the current
locale. See L<perllocale>. You may use C<\w>, C<\W>, C<\s>, C<\S>,
C<\d>, and C<\D> within character classes, but if you try to use them
as endpoints of a range, that's not a range, the "-" is understood
literally. If Unicode is in effect, C<\s> matches also "\x{85}",
"\x{2028}, and "\x{2029}", see L<perlunicode> for more details about
C<\pP>, C<\PP>, and C<\X>, and L<perluniintro> about Unicode in general.
You can define your own C<\p> and C<\P> properties, see L<perlunicode>.
X<\w> X<\W> X<word>
The POSIX character class syntax
X<character class>
[:class:]
is also available. Note that the C<[> and C<]> braces are I<literal>;
they must always be used within a character class expression.
# this is correct:
$string =~ /[[:alpha:]]/;
# this is not, and will generate a warning:
$string =~ /[:alpha:]/;
The available classes and their backslash equivalents (if available) are
as follows:
X<character class>
X<alpha> X<alnum> X<ascii> X<blank> X<cntrl> X<digit> X<graph>
X<lower> X<print> X<punct> X<space> X<upper> X<word> X<xdigit>
alpha
alnum
ascii
blank [1]
cntrl
digit \d
graph
lower
print
punct
space \s [2]
upper
word \w [3]
xdigit
=over
=item [1]
A GNU extension equivalent to C<[ \t]>, "all horizontal whitespace".
=item [2]
Not exactly equivalent to C<\s> since the C<[[:space:]]> includes
also the (very rare) "vertical tabulator", "\ck", chr(11).
=item [3]
A Perl extension, see above.
=back
For example use C<[:upper:]> to match all the uppercase characters.
Note that the C<[]> are part of the C<[::]> construct, not part of the
whole character class. For example:
[01[:alpha:]%]
matches zero, one, any alphabetic character, and the percentage sign.
The following equivalences to Unicode \p{} constructs and equivalent
backslash character classes (if available), will hold:
X<character class> X<\p> X<\p{}>
[[:...:]] \p{...} backslash
alpha IsAlpha
alnum IsAlnum
ascii IsASCII
blank IsSpace
cntrl IsCntrl
digit IsDigit \d
graph IsGraph
lower IsLower
print IsPrint
punct IsPunct
space IsSpace
IsSpacePerl \s
upper IsUpper
word IsWord
xdigit IsXDigit
For example C<[[:lower:]]> and C<\p{IsLower}> are equivalent.
If the C<utf8> pragma is not used but the C<locale> pragma is, the
classes correlate with the usual isalpha(3) interface (except for
"word" and "blank").
The assumedly non-obviously named classes are:
=over 4
=item cntrl
X<cntrl>
Any control character. Usually characters that don't produce output as
such but instead control the terminal somehow: for example newline and
backspace are control characters. All characters with ord() less than
32 are most often classified as control characters (assuming ASCII,
the ISO Latin character sets, and Unicode), as is the character with
the ord() value of 127 (C<DEL>).
=item graph
X<graph>
Any alphanumeric or punctuation (special) character.
=item print
X<print>
Any alphanumeric or punctuation (special) character or the space character.
=item punct
X<punct>
Any punctuation (special) character.
=item xdigit
X<xdigit>
Any hexadecimal digit. Though this may feel silly ([0-9A-Fa-f] would
work just fine) it is included for completeness.
=back
You can negate the [::] character classes by prefixing the class name
with a '^'. This is a Perl extension. For example:
X<character class, negation>
POSIX traditional Unicode
[[:^digit:]] \D \P{IsDigit}
[[:^space:]] \S \P{IsSpace}
[[:^word:]] \W \P{IsWord}
Perl respects the POSIX standard in that POSIX character classes are
only supported within a character class. The POSIX character classes
[.cc.] and [=cc=] are recognized but B<not> supported and trying to
use them will cause an error.
=head3 Assertions
Perl defines the following zero-width assertions:
X<zero-width assertion> X<assertion> X<regex, zero-width assertion>
X<regexp, zero-width assertion>
X<regular expression, zero-width assertion>
X<\b> X<\B> X<\A> X<\Z> X<\z> X<\G>
\b Match a word boundary
\B Match a non-(word boundary)
\A Match only at beginning of string
\Z Match only at end of string, or before newline at the end
\z Match only at end of string
\G Match only at pos() (e.g. at the end-of-match position
of prior m//g)
A word boundary (C<\b>) is a spot between two characters
that has a C<\w> on one side of it and a C<\W> on the other side
of it (in either order), counting the imaginary characters off the
beginning and end of the string as matching a C<\W>. (Within
character classes C<\b> represents backspace rather than a word
boundary, just as it normally does in any double-quoted string.)
The C<\A> and C<\Z> are just like "^" and "$", except that they
won't match multiple times when the C</m> modifier is used, while
"^" and "$" will match at every internal line boundary. To match
the actual end of the string and not ignore an optional trailing
newline, use C<\z>.
X<\b> X<\A> X<\Z> X<\z> X</m>
The C<\G> assertion can be used to chain global matches (using
C<m//g>), as described in L<perlop/"Regexp Quote-Like Operators">.
It is also useful when writing C<lex>-like scanners, when you have
several patterns that you want to match against consequent substrings
of your string, see the previous reference. The actual location
where C<\G> will match can also be influenced by using C<pos()> as
an lvalue: see L<perlfunc/pos>. Currently C<\G> is only fully
supported when anchored to the start of the pattern; while it
is permitted to use it elsewhere, as in C</(?<=\G..)./g>, some
such uses (C</.\G/g>, for example) currently cause problems, and
it is recommended that you avoid such usage for now.
X<\G>
=head3 Capture buffers
The bracketing construct C<( ... )> creates capture buffers. To
refer to the digit'th buffer use \<digit> within the
match. Outside the match use "$" instead of "\". (The
\<digit> notation works in certain circumstances outside
the match. See the warning below about \1 vs $1 for details.)
Referring back to another part of the match is called a
I<backreference>.
X<regex, capture buffer> X<regexp, capture buffer>
X<regular expression, capture buffer> X<backreference>
There is no limit to the number of captured substrings that you may
use. However Perl also uses \10, \11, etc. as aliases for \010,
\011, etc. (Recall that 0 means octal, so \011 is the character at
number 9 in your coded character set; which would be the 10th character,
a horizontal tab under ASCII.) Perl resolves this
ambiguity by interpreting \10 as a backreference only if at least 10
left parentheses have opened before it. Likewise \11 is a
backreference only if at least 11 left parentheses have opened
before it. And so on. \1 through \9 are always interpreted as
backreferences.
Additionally, as of Perl 5.10 you may use named capture buffers and named
backreferences. The notation is C<< (?<name>...) >> and C<< \k<name> >>
(you may also use single quotes instead of angle brackets to quote the
name). The only difference with named capture buffers and unnamed ones is
that multiple buffers may have the same name and that the contents of
named capture buffers is available via the C<%+> hash. When multiple
groups share the same name C<$+{name}> and C<< \k<name> >> refer to the
leftmost defined group, thus it's possible to do things with named capture
buffers that would otherwise require C<(??{})> code to accomplish. Named
capture buffers are numbered just as normal capture buffers are and may be
referenced via the magic numeric variables or via numeric backreferences
as well as by name.
Examples:
s/^([^ ]*) *([^ ]*)/$2 $1/; # swap first two words
/(.)\1/ # find first doubled char
and print "'$1' is the first doubled character\n";
/(?<char>.)\k<char>/ # ... a different way
and print "'$+{char}' is the first doubled character\n";
/(?<char>.)\1/ # ... mix and match
and print "'$1' is the first doubled character\n";
if (/Time: (..):(..):(..)/) { # parse out values
$hours = $1;
$minutes = $2;
$seconds = $3;
}
Several special variables also refer back to portions of the previous
match. C<$+> returns whatever the last bracket match matched.
C<$&> returns the entire matched string. (At one point C<$0> did
also, but now it returns the name of the program.) C<$`> returns
everything before the matched string. C<$'> returns everything
after the matched string. And C<$^N> contains whatever was matched by
the most-recently closed group (submatch). C<$^N> can be used in
extended patterns (see below), for example to assign a submatch to a
variable.
X<$+> X<$^N> X<$&> X<$`> X<$'>
The numbered match variables ($1, $2, $3, etc.) and the related punctuation
set (C<$+>, C<$&>, C<$`>, C<$'>, and C<$^N>) are all dynamically scoped
until the end of the enclosing block or until the next successful
match, whichever comes first. (See L<perlsyn/"Compound Statements">.)
X<$+> X<$^N> X<$&> X<$`> X<$'>
X<$1> X<$2> X<$3> X<$4> X<$5> X<$6> X<$7> X<$8> X<$9>
B<NOTE>: failed matches in Perl do not reset the match variables,
which makes it easier to write code that tests for a series of more
specific cases and remembers the best match.
B<WARNING>: Once Perl sees that you need one of C<$&>, C<$`>, or
C<$'> anywhere in the program, it has to provide them for every
pattern match. This may substantially slow your program. Perl
uses the same mechanism to produce $1, $2, etc, so you also pay a
price for each pattern that contains capturing parentheses. (To
avoid this cost while retaining the grouping behaviour, use the
extended regular expression C<(?: ... )> instead.) But if you never
use C<$&>, C<$`> or C<$'>, then patterns I<without> capturing
parentheses will not be penalized. So avoid C<$&>, C<$'>, and C<$`>
if you can, but if you can't (and some algorithms really appreciate
them), once you've used them once, use them at will, because you've
already paid the price. As of 5.005, C<$&> is not so costly as the
other two.
X<$&> X<$`> X<$'>
Backslashed metacharacters in Perl are alphanumeric, such as C<\b>,
C<\w>, C<\n>. Unlike some other regular expression languages, there
are no backslashed symbols that aren't alphanumeric. So anything
that looks like \\, \(, \), \<, \>, \{, or \} is always
interpreted as a literal character, not a metacharacter. This was
once used in a common idiom to disable or quote the special meanings
of regular expression metacharacters in a string that you want to
use for a pattern. Simply quote all non-"word" characters:
$pattern =~ s/(\W)/\\$1/g;
(If C<use locale> is set, then this depends on the current locale.)
Today it is more common to use the quotemeta() function or the C<\Q>
metaquoting escape sequence to disable all metacharacters' special
meanings like this:
/$unquoted\Q$quoted\E$unquoted/
Beware that if you put literal backslashes (those not inside
interpolated variables) between C<\Q> and C<\E>, double-quotish
backslash interpolation may lead to confusing results. If you
I<need> to use literal backslashes within C<\Q...\E>,
consult L<perlop/"Gory details of parsing quoted constructs">.
=head2 Extended Patterns
Perl also defines a consistent extension syntax for features not
found in standard tools like B<awk> and B<lex>. The syntax is a
pair of parentheses with a question mark as the first thing within
the parentheses. The character after the question mark indicates
the extension.
The stability of these extensions varies widely. Some have been
part of the core language for many years. Others are experimental
and may change without warning or be completely removed. Check
the documentation on an individual feature to verify its current
status.
A question mark was chosen for this and for the minimal-matching
construct because 1) question marks are rare in older regular
expressions, and 2) whenever you see one, you should stop and
"question" exactly what is going on. That's psychology...
=over 10
=item C<(?#text)>
X<(?#)>
A comment. The text is ignored. If the C</x> modifier enables
whitespace formatting, a simple C<#> will suffice. Note that Perl closes
the comment as soon as it sees a C<)>, so there is no way to put a literal
C<)> in the comment.
=item C<(?imsx-imsx)>
X<(?)>
One or more embedded pattern-match modifiers, to be turned on (or
turned off, if preceded by C<->) for the remainder of the pattern or
the remainder of the enclosing pattern group (if any). This is
particularly useful for dynamic patterns, such as those read in from a
configuration file, read in as an argument, are specified in a table
somewhere, etc. Consider the case that some of which want to be case
sensitive and some do not. The case insensitive ones need to include
merely C<(?i)> at the front of the pattern. For example:
$pattern = "foobar";
if ( /$pattern/i ) { }
# more flexible:
$pattern = "(?i)foobar";
if ( /$pattern/ ) { }
These modifiers are restored at the end of the enclosing group. For example,
( (?i) blah ) \s+ \1
will match a repeated (I<including the case>!) word C<blah> in any
case, assuming C<x> modifier, and no C<i> modifier outside this
group.
=item C<(?:pattern)>
X<(?:)>
=item C<(?imsx-imsx:pattern)>
This is for clustering, not capturing; it groups subexpressions like
"()", but doesn't make backreferences as "()" does. So
@fields = split(/\b(?:a|b|c)\b/)
is like
@fields = split(/\b(a|b|c)\b/)
but doesn't spit out extra fields. It's also cheaper not to capture
characters if you don't need to.
Any letters between C<?> and C<:> act as flags modifiers as with
C<(?imsx-imsx)>. For example,
/(?s-i:more.*than).*million/i
is equivalent to the more verbose
/(?:(?s-i)more.*than).*million/i
=item C<(?=pattern)>
X<(?=)> X<look-ahead, positive> X<lookahead, positive>
A zero-width positive look-ahead assertion. For example, C</\w+(?=\t)/>
matches a word followed by a tab, without including the tab in C<$&>.
=item C<(?!pattern)>
X<(?!)> X<look-ahead, negative> X<lookahead, negative>
A zero-width negative look-ahead assertion. For example C</foo(?!bar)/>
matches any occurrence of "foo" that isn't followed by "bar". Note
however that look-ahead and look-behind are NOT the same thing. You cannot
use this for look-behind.
If you are looking for a "bar" that isn't preceded by a "foo", C</(?!foo)bar/>
will not do what you want. That's because the C<(?!foo)> is just saying that
the next thing cannot be "foo"--and it's not, it's a "bar", so "foobar" will
match. You would have to do something like C</(?!foo)...bar/> for that. We
say "like" because there's the case of your "bar" not having three characters
before it. You could cover that this way: C</(?:(?!foo)...|^.{0,2})bar/>.
Sometimes it's still easier just to say:
if (/bar/ && $` !~ /foo$/)
For look-behind see below.
=item C<(?<=pattern)>
X<(?<=)> X<look-behind, positive> X<lookbehind, positive>
A zero-width positive look-behind assertion. For example, C</(?<=\t)\w+/>
matches a word that follows a tab, without including the tab in C<$&>.
Works only for fixed-width look-behind.
=item C<(?<!pattern)>
X<(?<!)> X<look-behind, negative> X<lookbehind, negative>
A zero-width negative look-behind assertion. For example C</(?<!bar)foo/>
matches any occurrence of "foo" that does not follow "bar". Works
only for fixed-width look-behind.
=item C<(?'NAME'pattern)>
=item C<< (?<NAME>pattern) >>
X<< (?<NAME>) >> X<(?'NAME')> X<named capture> X<capture>
A named capture buffer. Identical in every respect to normal capturing
parens C<()> but for the additional fact that C<%+> may be used after
a succesful match to refer to a named buffer. See C<perlvar> for more
details on the C<%+> hash.
If multiple distinct capture buffers have the same name then the
$+{NAME} will refer to the leftmost defined buffer in the match.
The forms C<(?'NAME'pattern)> and C<(?<NAME>pattern)> are equivalent.
B<NOTE:> While the notation of this construct is the same as the similar
function in .NET regexes, the behavior is not, in Perl the buffers are
numbered sequentially regardless of being named or not. Thus in the
pattern
/(x)(?<foo>y)(z)/
$+{foo} will be the same as $2, and $3 will contain 'z' instead of
the opposite which is what a .NET regex hacker might expect.
Currently NAME is restricted to word chars only. In other words, it
must match C</^\w+$/>.
=item C<< \k<name> >>
=item C<< \k'name' >>
Named backreference. Similar to numeric backreferences, except that
the group is designated by name and not number. If multiple groups
have the same name then it refers to the leftmost defined group in
the current match.
It is an error to refer to a name not defined by a C<(?<NAME>)>
earlier in the pattern.
Both forms are equivalent.
=item C<(?{ code })>
X<(?{})> X<regex, code in> X<regexp, code in> X<regular expression, code in>
B<WARNING>: This extended regular expression feature is considered
experimental, and may be changed without notice. Code executed that
has side effects may not perform identically from version to version
due to the effect of future optimisations in the regex engine.
This zero-width assertion evaluates any embedded Perl code. It
always succeeds, and its C<code> is not interpolated. Currently,
the rules to determine where the C<code> ends are somewhat convoluted.
This feature can be used together with the special variable C<$^N> to
capture the results of submatches in variables without having to keep
track of the number of nested parentheses. For example:
$_ = "The brown fox jumps over the lazy dog";
/the (\S+)(?{ $color = $^N }) (\S+)(?{ $animal = $^N })/i;
print "color = $color, animal = $animal\n";
Inside the C<(?{...})> block, C<$_> refers to the string the regular
expression is matching against. You can also use C<pos()> to know what is
the current position of matching within this string.
The C<code> is properly scoped in the following sense: If the assertion
is backtracked (compare L<"Backtracking">), all changes introduced after
C<local>ization are undone, so that
$_ = 'a' x 8;
m<
(?{ $cnt = 0 }) # Initialize $cnt.
(
a
(?{
local $cnt = $cnt + 1; # Update $cnt, backtracking-safe.
})
)*
aaaa
(?{ $res = $cnt }) # On success copy to non-localized
# location.
>x;
will set C<$res = 4>. Note that after the match, $cnt returns to the globally
introduced value, because the scopes that restrict C<local> operators
are unwound.
This assertion may be used as a C<(?(condition)yes-pattern|no-pattern)>
switch. If I<not> used in this way, the result of evaluation of
C<code> is put into the special variable C<$^R>. This happens
immediately, so C<$^R> can be used from other C<(?{ code })> assertions
inside the same regular expression.
The assignment to C<$^R> above is properly localized, so the old
value of C<$^R> is restored if the assertion is backtracked; compare
L<"Backtracking">.
Due to an unfortunate implementation issue, the Perl code contained in these
blocks is treated as a compile time closure that can have seemingly bizarre
consequences when used with lexically scoped variables inside of subroutines
or loops. There are various workarounds for this, including simply using
global variables instead. If you are using this construct and strange results
occur then check for the use of lexically scoped variables.
For reasons of security, this construct is forbidden if the regular
expression involves run-time interpolation of variables, unless the
perilous C<use re 'eval'> pragma has been used (see L<re>), or the
variables contain results of C<qr//> operator (see
L<perlop/"qr/STRING/imosx">).
This restriction is because of the wide-spread and remarkably convenient
custom of using run-time determined strings as patterns. For example:
$re = <>;
chomp $re;
$string =~ /$re/;
Before Perl knew how to execute interpolated code within a pattern,
this operation was completely safe from a security point of view,
although it could raise an exception from an illegal pattern. If
you turn on the C<use re 'eval'>, though, it is no longer secure,
so you should only do so if you are also using taint checking.
Better yet, use the carefully constrained evaluation within a Safe
compartment. See L<perlsec> for details about both these mechanisms.
Because perl's regex engine is not currently re-entrant, interpolated
code may not invoke the regex engine either directly with C<m//> or C<s///>),
or indirectly with functions such as C<split>.
=item C<(??{ code })>
X<(??{})>
X<regex, postponed> X<regexp, postponed> X<regular expression, postponed>
B<WARNING>: This extended regular expression feature is considered
experimental, and may be changed without notice. Code executed that
has side effects may not perform identically from version to version
due to the effect of future optimisations in the regex engine.
This is a "postponed" regular subexpression. The C<code> is evaluated
at run time, at the moment this subexpression may match. The result
of evaluation is considered as a regular expression and matched as
if it were inserted instead of this construct. Note that this means
that the contents of capture buffers defined inside an eval'ed pattern
are not available outside of the pattern, and vice versa, there is no
way for the inner pattern to refer to a capture buffer defined outside.
Thus,
('a' x 100)=~/(??{'(.)' x 100})/
B<will> match, it will B<not> set $1.
The C<code> is not interpolated. As before, the rules to determine
where the C<code> ends are currently somewhat convoluted.
The following pattern matches a parenthesized group:
$re = qr{
\(
(?:
(?> [^()]+ ) # Non-parens without backtracking
|
(??{ $re }) # Group with matching parens
)*
\)
}x;
See also C<(?PARNO)> for a different, more efficient way to accomplish
the same task.
Because perl's regex engine is not currently re-entrant, delayed
code may not invoke the regex engine either directly with C<m//> or C<s///>),
or indirectly with functions such as C<split>.
Recursing deeper than 50 times without consuming any input string will
result in a fatal error. The maximum depth is compiled into perl, so
changing it requires a custom build.
=item C<(?PARNO)> C<(?R)> C<(?0)>
X<(?PARNO)> X<(?1)> X<(?R)> X<(?0)>
X<regex, recursive> X<regexp, recursive> X<regular expression, recursive>
Similar to C<(??{ code })> except it does not involve compiling any code,
instead it treats the contents of a capture buffer as an independent
pattern that must match at the current position. Capture buffers
contained by the pattern will have the value as determined by the
outermost recursion.
PARNO is a sequence of digits (not starting with 0) whose value reflects
the paren-number of the capture buffer to recurse to. C<(?R)> recurses to
the beginning of the whole pattern. C<(?0)> is an alternate syntax for
C<(?R)>.
The following pattern matches a function foo() which may contain
balanced parentheses as the argument.
$re = qr{ ( # paren group 1 (full function)
foo
( # paren group 2 (parens)
\(
( # paren group 3 (contents of parens)
(?:
(?> [^()]+ ) # Non-parens without backtracking
|
(?2) # Recurse to start of paren group 2
)*
)
\)
)
)
}x;
If the pattern was used as follows
'foo(bar(baz)+baz(bop))'=~/$re/
and print "\$1 = $1\n",
"\$2 = $2\n",
"\$3 = $3\n";
the output produced should be the following:
$1 = foo(bar(baz)+baz(bop))
$2 = (bar(baz)+baz(bop))
$3 = bar(baz)+baz(bop)
If there is no corresponding capture buffer defined, then it is a
fatal error. Recursing deeper than 50 times without consuming any input
string will also result in a fatal error. The maximum depth is compiled
into perl, so changing it requires a custom build.
B<Note> that this pattern does not behave the same way as the equivalent
PCRE or Python construct of the same form. In perl you can backtrack into
a recursed group, in PCRE and Python the recursed into group is treated
as atomic. Also, constructs like (?i:(?1)) or (?:(?i)(?1)) do not affect
the pattern being recursed into.
=item C<(?&NAME)>
X<(?&NAME)>
Recurse to a named subpattern. Identical to (?PARNO) except that the
parenthesis to recurse to is determined by name. If multiple parens have
the same name, then it recurses to the leftmost.
It is an error to refer to a name that is not declared somewhere in the
pattern.
=item C<(?FAIL)> C<(?F)>
X<(?FAIL)> X<(?F)>
This pattern matches nothing and always fails. It can be used to force the
engine to backtrack. It is equivalent to C<(?!)>, but easier to read. In
fact, C<(?!)> gets optimised into C<(?FAIL)> internally.
It is probably useful only when combined with C<(?{})> or C<(??{})>.
=item C<< (?>pattern) >>
X<backtrack> X<backtracking> X<atomic> X<possessive>
An "independent" subexpression, one which matches the substring
that a I<standalone> C<pattern> would match if anchored at the given
position, and it matches I<nothing other than this substring>. This
construct is useful for optimizations of what would otherwise be
"eternal" matches, because it will not backtrack (see L<"Backtracking">).
It may also be useful in places where the "grab all you can, and do not
give anything back" semantic is desirable.
For example: C<< ^(?>a*)ab >> will never match, since C<< (?>a*) >>
(anchored at the beginning of string, as above) will match I<all>
characters C<a> at the beginning of string, leaving no C<a> for
C<ab> to match. In contrast, C<a*ab> will match the same as C<a+b>,
since the match of the subgroup C<a*> is influenced by the following
group C<ab> (see L<"Backtracking">). In particular, C<a*> inside
C<a*ab> will match fewer characters than a standalone C<a*>, since
this makes the tail match.
An effect similar to C<< (?>pattern) >> may be achieved by writing
C<(?=(pattern))\1>. This matches the same substring as a standalone
C<a+>, and the following C<\1> eats the matched string; it therefore
makes a zero-length assertion into an analogue of C<< (?>...) >>.
(The difference between these two constructs is that the second one
uses a capturing group, thus shifting ordinals of backreferences
in the rest of a regular expression.)
Consider this pattern:
m{ \(
(
[^()]+ # x+
|
\( [^()]* \)
)+
\)
}x
That will efficiently match a nonempty group with matching parentheses
two levels deep or less. However, if there is no such group, it
will take virtually forever on a long string. That's because there
are so many different ways to split a long string into several
substrings. This is what C<(.+)+> is doing, and C<(.+)+> is similar
to a subpattern of the above pattern. Consider how the pattern
above detects no-match on C<((()aaaaaaaaaaaaaaaaaa> in several
seconds, but that each extra letter doubles this time. This
exponential performance will make it appear that your program has
hung. However, a tiny change to this pattern
m{ \(
(
(?> [^()]+ ) # change x+ above to (?> x+ )
|
\( [^()]* \)
)+