Debian Codegraph @

upstream/opensuse-tumbleweed/man1/perlre.1

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man v6.0.2 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\"
56 .\" Required to disable full justification in groff 1.23.0.
57 .if n .ds AD l
58 .\" ========================================================================
59 .\"
60 .IX Title "PERLRE 1"
61 .TH PERLRE 1 2026-03-09 "perl v5.42.1" "Perl Programmers Reference Guide"
62 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
63 .\" way too many mistakes in technical documents.
64 .if n .ad l
65 .nh
66 .SH NAME
67 perlre \- Perl regular expressions
68 .IX Xref "regular expression regex regexp"
69 .SH DESCRIPTION
70 .IX Header "DESCRIPTION"
71 This page describes the syntax of regular expressions in Perl.
72 .PP
73 If you haven\*(Aqt used regular expressions before, a tutorial introduction
74 is available in perlretut. If you know just a little about them,
75 a quick\-start introduction is available in perlrequick.
76 .PP
77 Except for "The Basics" section, this page assumes you are familiar
78 with regular expression basics, like what is a "pattern", what does it
79 look like, and how it is basically used. For a reference on how they
80 are used, plus various examples of the same, see discussions of \f(CW\*(C`m//\*(C'\fR,
81 \&\f(CW\*(C`s///\*(C'\fR, \f(CW\*(C`qr//\*(C'\fR and \f(CW"??"\fR in "Regexp Quote\-Like Operators" in perlop.
82 .PP
83 New in v5.22, \f(CW\*(C`use re \*(Aqstrict\*(Aq\*(C'\fR applies stricter
84 rules than otherwise when compiling regular expression patterns. It can
85 find things that, while legal, may not be what you intended.
86 .SS "The Basics"
87 .IX Xref "regular expression, version 8 regex, version 8 regexp, version 8"
88 .IX Subsection "The Basics"
89 Regular expressions are strings with the very particular syntax and
90 meaning described in this document and auxiliary documents referred to
91 by this one. The strings are called "patterns". Patterns are used to
92 determine if some other string, called the "target", has (or doesn\*(Aqt
93 have) the characteristics specified by the pattern. We call this
94 "matching" the target string against the pattern. Usually the match is
95 done by having the target be the first operand, and the pattern be the
96 second operand, of one of the two binary operators \f(CW\*(C`=~\*(C'\fR and \f(CW\*(C`!~\*(C'\fR,
97 listed in "Binding Operators" in perlop; and the pattern will have been
98 converted from an ordinary string by one of the operators in
99 "Regexp Quote\-Like Operators" in perlop, like so:
100 .PP
101 .Vb 1
102 \& $foo =~ m/abc/
103 .Ve
104 .PP
105 This evaluates to true if and only if the string in the variable \f(CW$foo\fR
106 contains somewhere in it, the sequence of characters "a", "b", then "c".
107 (The \f(CW\*(C`=~ m\*(C'\fR, or match operator, is described in
108 "m/PATTERN/msixpodualngc" in perlop.)
109 .PP
110 Patterns that aren\*(Aqt already stored in some variable must be delimited,
111 at both ends, by delimiter characters. These are often, as in the
112 example above, forward slashes, and the typical way a pattern is written
113 in documentation is with those slashes. In most cases, the delimiter
114 is the same character, fore and aft, but there are a few cases where a
115 character looks like it has a mirror\-image mate, where the opening
116 version is the beginning delimiter, and the closing one is the ending
117 delimiter, like
118 .PP
119 .Vb 1
120 \& $foo =~ m<abc>
121 .Ve
122 .PP
123 Most times, the pattern is evaluated in double\-quotish context, but it
124 is possible to choose delimiters to force single\-quotish, like
125 .PP
126 .Vb 1
127 \& $foo =~ m\*(Aqabc\*(Aq
128 .Ve
129 .PP
130 If the pattern contains its delimiter within it, that delimiter must be
131 escaped. Prefixing it with a backslash (\fIe.g.\fR, \f(CW"/foo\e/bar/"\fR)
132 serves this purpose.
133 .PP
134 Any single character in a pattern matches that same character in the
135 target string, unless the character is a \fImetacharacter\fR with a special
136 meaning described in this document. A sequence of non\-metacharacters
137 matches the same sequence in the target string, as we saw above with
138 \&\f(CW\*(C`m/abc/\*(C'\fR.
139 .PP
140 Only a few characters (all of them being ASCII punctuation characters)
141 are metacharacters. The most commonly used one is a dot \f(CW"."\fR, which
142 normally matches almost any character (including a dot itself).
143 .PP
144 You can cause characters that normally function as metacharacters to be
145 interpreted literally by prefixing them with a \f(CW"\e"\fR, just like the
146 pattern\*(Aqs delimiter must be escaped if it also occurs within the
147 pattern. Thus, \f(CW"\e."\fR matches just a literal dot, \f(CW"."\fR instead of
148 its normal meaning. This means that the backslash is also a
149 metacharacter, so \f(CW"\e\e"\fR matches a single \f(CW"\e"\fR. And a sequence that
150 contains an escaped metacharacter matches the same sequence (but without
151 the escape) in the target string. So, the pattern \f(CW\*(C`/blur\e\efl/\*(C'\fR would
152 match any target string that contains the sequence \f(CW"blur\efl"\fR.
153 .PP
154 The metacharacter \f(CW"|"\fR is used to match one thing or another. Thus
155 .PP
156 .Vb 1
157 \& $foo =~ m/this|that/
158 .Ve
159 .PP
160 is TRUE if and only if \f(CW$foo\fR contains either the sequence \f(CW"this"\fR or
161 the sequence \f(CW"that"\fR. Like all metacharacters, prefixing the \f(CW"|"\fR
162 with a backslash makes it match the plain punctuation character; in its
163 case, the VERTICAL LINE.
164 .PP
165 .Vb 1
166 \& $foo =~ m/this\e|that/
167 .Ve
168 .PP
169 is TRUE if and only if \f(CW$foo\fR contains the sequence \f(CW"this|that"\fR.
170 .PP
171 You aren\*(Aqt limited to just a single \f(CW"|"\fR.
172 .PP
173 .Vb 1
174 \& $foo =~ m/fee|fie|foe|fum/
175 .Ve
176 .PP
177 is TRUE if and only if \f(CW$foo\fR contains any of those 4 sequences from
178 the children\*(Aqs story "Jack and the Beanstalk".
179 .PP
180 As you can see, the \f(CW"|"\fR binds less tightly than a sequence of
181 ordinary characters. We can override this by using the grouping
182 metacharacters, the parentheses \f(CW"("\fR and \f(CW")"\fR.
183 .PP
184 .Vb 1
185 \& $foo =~ m/th(is|at) thing/
186 .Ve
187 .PP
188 is TRUE if and only if \f(CW$foo\fR contains either the sequence \f(CW"this\ thing"\fR or the sequence \f(CW"that\ thing"\fR. The portions of the string
189 that match the portions of the pattern enclosed in parentheses are
190 normally made available separately for use later in the pattern,
191 substitution, or program. This is called "capturing", and it can get
192 complicated. See "Capture groups".
193 .PP
194 The first alternative includes everything from the last pattern
195 delimiter (\f(CW"("\fR, \f(CW"(?:"\fR (described later), \fIetc\fR. or the beginning
196 of the pattern) up to the first \f(CW"|"\fR, and the last alternative
197 contains everything from the last \f(CW"|"\fR to the next closing pattern
198 delimiter. That\*(Aqs why it\*(Aqs common practice to include alternatives in
199 parentheses: to minimize confusion about where they start and end.
200 .PP
201 Alternatives are tried from left to right, so the first
202 alternative found for which the entire expression matches, is the one that
203 is chosen. This means that alternatives are not necessarily greedy. For
204 example: when matching \f(CW\*(C`foo|foot\*(C'\fR against \f(CW"barefoot"\fR, only the \f(CW"foo"\fR
205 part will match, as that is the first alternative tried, and it successfully
206 matches the target string. (This might not seem important, but it is
207 important when you are capturing matched text using parentheses.)
208 .PP
209 Besides taking away the special meaning of a metacharacter, a prefixed
210 backslash changes some letter and digit characters away from matching
211 just themselves to instead have special meaning. These are called
212 "escape sequences", and all such are described in perlrebackslash. A
213 backslash sequence (of a letter or digit) that doesn\*(Aqt currently have
214 special meaning to Perl will raise a warning if warnings are enabled,
215 as those are reserved for potential future use.
216 .PP
217 One such sequence is \f(CW\*(C`\eb\*(C'\fR, which matches a boundary of some sort.
218 \&\f(CW\*(C`\eb{wb}\*(C'\fR and a few others give specialized types of boundaries.
219 (They are all described in detail starting at
220 "\eb{}, \eb, \eB{}, \eB" in perlrebackslash.) Note that these don\*(Aqt match
221 characters, but the zero\-width spaces between characters. They are an
222 example of a zero\-width assertion. Consider again,
223 .PP
224 .Vb 1
225 \& $foo =~ m/fee|fie|foe|fum/
226 .Ve
227 .PP
228 It evaluates to TRUE if, besides those 4 words, any of the sequences
229 "feed", "field", "Defoe", "fume", and many others are in \f(CW$foo\fR. By
230 judicious use of \f(CW\*(C`\eb\*(C'\fR (or better (because it is designed to handle
231 natural language) \f(CW\*(C`\eb{wb}\*(C'\fR), we can make sure that only the Giant\*(Aqs
232 words are matched:
233 .PP
234 .Vb 2
235 \& $foo =~ m/\eb(fee|fie|foe|fum)\eb/
236 \& $foo =~ m/\eb{wb}(fee|fie|foe|fum)\eb{wb}/
237 .Ve
238 .PP
239 The final example shows that the characters \f(CW"{"\fR and \f(CW"}"\fR are
240 metacharacters.
241 .PP
242 Another use for escape sequences is to specify characters that cannot
243 (or which you prefer not to) be written literally. These are described
244 in detail in "Character Escapes" in perlrebackslash, but the next three
245 paragraphs briefly describe some of them.
246 .PP
247 Various control characters can be written in C language style: \f(CW"\en"\fR
248 matches a newline, \f(CW"\et"\fR a tab, \f(CW"\er"\fR a carriage return, \f(CW"\ef"\fR a
249 form feed, \fIetc\fR.
250 .PP
251 More generally, \f(CW\*(C`\e\fR\f(CInnn\fR\f(CW\*(C'\fR, where \fInnn\fR is a string of three octal
252 digits, matches the character whose native code point is \fInnn\fR. You
253 can easily run into trouble if you don\*(Aqt have exactly three digits. So
254 always use three, or since Perl 5.14, you can use \f(CW\*(C`\eo{...}\*(C'\fR to specify
255 any number of octal digits.
256 .PP
257 Similarly, \f(CW\*(C`\ex\fR\f(CInn\fR\f(CW\*(C'\fR, where \fInn\fR are hexadecimal digits, matches the
258 character whose native ordinal is \fInn\fR. Again, not using exactly two
259 digits is a recipe for disaster, but you can use \f(CW\*(C`\ex{...}\*(C'\fR to specify
260 any number of hex digits.
261 .PP
262 Besides being a metacharacter, the \f(CW"."\fR is an example of a "character
263 class", something that can match any single character of a given set of
264 them. In its case, the set is just about all possible characters. Perl
265 predefines several character classes besides the \f(CW"."\fR; there is a
266 separate reference page about just these, perlrecharclass.
267 .PP
268 You can define your own custom character classes, by putting into your
269 pattern in the appropriate place(s), a list of all the characters you
270 want in the set. You do this by enclosing the list within \f(CW\*(C`[]\*(C'\fR bracket
271 characters. These are called "bracketed character classes" when we are
272 being precise, but often the word "bracketed" is dropped. (Dropping it
273 usually doesn\*(Aqt cause confusion.) This means that the \f(CW"["\fR character
274 is another metacharacter. It doesn\*(Aqt match anything just by itself; it
275 is used only to tell Perl that what follows it is a bracketed character
276 class. If you want to match a literal left square bracket, you must
277 escape it, like \f(CW"\e["\fR. The matching \f(CW"]"\fR is also a metacharacter;
278 again it doesn\*(Aqt match anything by itself, but just marks the end of
279 your custom class to Perl. It is an example of a "sometimes
280 metacharacter". It isn\*(Aqt a metacharacter if there is no corresponding
281 \&\f(CW"["\fR, and matches its literal self:
282 .PP
283 .Vb 1
284 \& print "]" =~ /]/; # prints 1
285 .Ve
286 .PP
287 The list of characters within the character class gives the set of
288 characters matched by the class. \f(CW"[abc]"\fR matches a single "a" or "b"
289 or "c". But if the first character after the \f(CW"["\fR is \f(CW"^"\fR, the
290 class instead matches any character not in the list. Within a list, the
291 \&\f(CW"\-"\fR character specifies a range of characters, so that \f(CW\*(C`a\-z\*(C'\fR
292 represents all characters between "a" and "z", inclusive. If you want
293 either \f(CW"\-"\fR or \f(CW"]"\fR itself to be a member of a class, put it at the
294 start of the list (possibly after a \f(CW"^"\fR), or escape it with a
295 backslash. \f(CW"\-"\fR is also taken literally when it is at the end of the
296 list, just before the closing \f(CW"]"\fR. (The following all specify the
297 same class of three characters: \f(CW\*(C`[\-az]\*(C'\fR, \f(CW\*(C`[az\-]\*(C'\fR, and \f(CW\*(C`[a\e\-z]\*(C'\fR. All
298 are different from \f(CW\*(C`[a\-z]\*(C'\fR, which specifies a class containing
299 twenty\-six characters, even on EBCDIC\-based character sets.)
300 .PP
301 There is lots more to bracketed character classes; full details are in
302 "Bracketed Character Classes" in perlrecharclass.
303 .PP
304 \fIMetacharacters\fR
305 .IX Xref "metacharacter \\ ^ . $ | ( () [ []"
306 .IX Subsection "Metacharacters"
307 .PP
308 "The Basics" introduced some of the metacharacters. This section
309 gives them all. Most of them have the same meaning as in the \fIegrep\fR
310 command.
311 .PP
312 Only the \f(CW"\e"\fR is always a metacharacter. The others are metacharacters
313 just sometimes. The following tables lists all of them, summarizes
314 their use, and gives the contexts where they are metacharacters.
315 Outside those contexts or if prefixed by a \f(CW"\e"\fR, they match their
316 corresponding punctuation character. In some cases, their meaning
317 varies depending on various pattern modifiers that alter the default
318 behaviors. See "Modifiers".
319 .PP
320 .Vb 10
321 \& PURPOSE WHERE
322 \& \e Escape the next character Always, except when
323 \& escaped by another \e
324 \& ^ Match the beginning of the string Not in []
325 \& (or line, if /m is used)
326 \& ^ Complement the [] class At the beginning of []
327 \& . Match any single character except newline Not in []
328 \& (under /s, includes newline)
329 \& $ Match the end of the string Not in [], but can
330 \& (or before newline at the end of the mean interpolate a
331 \& string; or before any newline if /m is scalar
332 \& used)
333 \& | Alternation Not in []
334 \& () Grouping Not in []
335 \& [ Start Bracketed Character class Not in []
336 \& ] End Bracketed Character class Only in [], and
337 \& not first
338 \& * Matches the preceding element 0 or more Not in []
339 \& times
340 \& + Matches the preceding element 1 or more Not in []
341 \& times
342 \& ? Matches the preceding element 0 or 1 Not in []
343 \& times
344 \& { Starts a sequence that gives number(s) Not in []
345 \& of times the preceding element can be
346 \& matched
347 \& { when following certain escape sequences
348 \& starts a modifier to the meaning of the
349 \& sequence
350 \& } End sequence started by {
351 \& \- Indicates a range Only in [] interior
352 \& # Beginning of comment, extends to line end Only with /x modifier
353 .Ve
354 .PP
355 Notice that most of the metacharacters lose their special meaning when
356 they occur in a bracketed character class, except \f(CW"^"\fR has a different
357 meaning when it is at the beginning of such a class. And \f(CW"\-"\fR and \f(CW"]"\fR
358 are metacharacters only at restricted positions within bracketed
359 character classes; while \f(CW"}"\fR is a metacharacter only when closing a
360 special construct started by \f(CW"{"\fR.
361 .PP
362 In double\-quotish context, as is usually the case, you need to be
363 careful about \f(CW"$"\fR and the non\-metacharacter \f(CW"@"\fR. Those could
364 interpolate variables, which may or may not be what you intended.
365 .PP
366 These rules were designed for compactness of expression, rather than
367 legibility and maintainability. The "/x and /xx" pattern
368 modifiers allow you to insert white space to improve readability. And
369 use of \f(CW\*(C`re\ \*(Aqstrict\*(Aq\*(C'\fR adds extra checking to
370 catch some typos that might silently compile into something unintended.
371 .PP
372 By default, the \f(CW"^"\fR character is guaranteed to match only the
373 beginning of the string, the \f(CW"$"\fR character only the end (or before the
374 newline at the end), and Perl does certain optimizations with the
375 assumption that the string contains only one line. Embedded newlines
376 will not be matched by \f(CW"^"\fR or \f(CW"$"\fR. You may, however, wish to treat a
377 string as a multi\-line buffer, such that the \f(CW"^"\fR will match after any
378 newline within the string (except if the newline is the last character in
379 the string), and \f(CW"$"\fR will match before any newline. At the
380 cost of a little more overhead, you can do this by using the
381 \&\f(CW"/m"\fR modifier on the pattern match operator. (Older programs
382 did this by setting \f(CW$*\fR, but this option was removed in perl 5.10.)
383 .IX Xref "^ $ m"
384 .PP
385 To simplify multi\-line substitutions, the \f(CW"."\fR character never matches a
386 newline unless you use the \f(CW\*(C`/s\*(C'\fR modifier, which in effect tells
387 Perl to pretend the string is a single line\-\-even if it isn\*(Aqt.
388 .IX Xref ". s"
389 .SS Modifiers
390 .IX Subsection "Modifiers"
391 \fIOverview\fR
392 .IX Subsection "Overview"
393 .PP
394 The default behavior for matching can be changed, using various
395 modifiers. Modifiers that relate to the interpretation of the pattern
396 are listed just below. Modifiers that alter the way a pattern is used
397 by Perl are detailed in "Regexp Quote\-Like Operators" in perlop and
398 "Gory details of parsing quoted constructs" in perlop. Modifiers can be added
399 dynamically; see "Extended Patterns" below.
400 .ie n .IP "\fR\fB""m""\fR\fB\fR" 4
401 .el .IP \fR\f(CBm\fR\fB\fR 4
402 .IX Xref " m regex, multiline regexp, multiline regular expression, multiline"
403 .IX Item "m"
404 Treat the string being matched against as multiple lines. That is, change \f(CW"^"\fR and \f(CW"$"\fR from matching
405 the start of the string\*(Aqs first line and the end of its last line to
406 matching the start and end of each line within the string.
407 .ie n .IP "\fR\fB""s""\fR\fB\fR" 4
408 .el .IP \fR\f(CBs\fR\fB\fR 4
409 .IX Xref " s regex, single-line regexp, single-line regular expression, single-line"
410 .IX Item "s"
411 Treat the string as single line. That is, change \f(CW"."\fR to match any character
412 whatsoever, even a newline, which normally it would not match.
413 .Sp
414 Used together, as \f(CW\*(C`/ms\*(C'\fR, they let the \f(CW"."\fR match any character whatsoever,
415 while still allowing \f(CW"^"\fR and \f(CW"$"\fR to match, respectively, just after
416 and just before newlines within the string.
417 .ie n .IP "\fR\fB""i""\fR\fB\fR" 4
418 .el .IP \fR\f(CBi\fR\fB\fR 4
419 .IX Xref " i regex, case-insensitive regexp, case-insensitive regular expression, case-insensitive"
420 .IX Item "i"
421 Do case\-insensitive pattern matching. For example, "A" will match "a"
422 under \f(CW\*(C`/i\*(C'\fR.
423 .Sp
424 If locale matching rules are in effect, the case map is taken from the
425 current
426 locale for code points less than 255, and from Unicode rules for larger
427 code points. However, matches that would cross the Unicode
428 rules/non\-Unicode rules boundary (ords 255/256) will not succeed, unless
429 the locale is a UTF\-8 one. See perllocale.
430 .Sp
431 There are a number of Unicode characters that match a sequence of
432 multiple characters under \f(CW\*(C`/i\*(C'\fR. For example,
433 \&\f(CW\*(C`LATIN SMALL LIGATURE FI\*(C'\fR should match the sequence \f(CW\*(C`fi\*(C'\fR. Perl is not
434 currently able to do this when the multiple characters are in the pattern and
435 are split between groupings, or when one or more are quantified. Thus
436 .Sp
437 .Vb 3
438 \& "\eN{LATIN SMALL LIGATURE FI}" =~ /fi/i; # Matches
439 \& "\eN{LATIN SMALL LIGATURE FI}" =~ /[fi][fi]/i; # Doesn\*(Aqt match!
440 \& "\eN{LATIN SMALL LIGATURE FI}" =~ /fi*/i; # Doesn\*(Aqt match!
441 \&
442 \& # The below doesn\*(Aqt match, and it isn\*(Aqt clear what $1 and $2 would
443 \& # be even if it did!!
444 \& "\eN{LATIN SMALL LIGATURE FI}" =~ /(f)(i)/i; # Doesn\*(Aqt match!
445 .Ve
446 .Sp
447 Perl doesn\*(Aqt match multiple characters in a bracketed
448 character class unless the character that maps to them is explicitly
449 mentioned, and it doesn\*(Aqt match them at all if the character class is
450 inverted, which otherwise could be highly confusing. See
451 "Bracketed Character Classes" in perlrecharclass, and
452 "Negation" in perlrecharclass.
453 .ie n .IP "\fR\fB""x""\fR\fB\fR and \fB\fR\fB""xx""\fR\fB\fR" 4
454 .el .IP "\fR\f(CBx\fR\fB\fR and \fB\fR\f(CBxx\fR\fB\fR" 4
455 .IX Xref " x"
456 .IX Item "x and xx"
457 Extend your pattern\*(Aqs legibility by permitting whitespace and comments.
458 Details in "/x and /xx"
459 .ie n .IP "\fR\fB""p""\fR\fB\fR" 4
460 .el .IP \fR\f(CBp\fR\fB\fR 4
461 .IX Xref " p regex, preserve regexp, preserve"
462 .IX Item "p"
463 Preserve the string matched such that \f(CW\*(C`${^PREMATCH}\*(C'\fR, \f(CW\*(C`${^MATCH}\*(C'\fR, and
464 \&\f(CW\*(C`${^POSTMATCH}\*(C'\fR are available for use after matching.
465 .Sp
466 In Perl 5.20 and higher this is ignored. Due to a new copy\-on\-write
467 mechanism, \f(CW\*(C`${^PREMATCH}\*(C'\fR, \f(CW\*(C`${^MATCH}\*(C'\fR, and \f(CW\*(C`${^POSTMATCH}\*(C'\fR will be available
468 after the match regardless of the modifier.
469 .ie n .IP "\fR\fB""a""\fR\fB\fR, \fB\fR\fB""d""\fR\fB\fR, \fB\fR\fB""l""\fR\fB\fR, and \fB\fR\fB""u""\fR\fB\fR" 4
470 .el .IP "\fR\f(CBa\fR\fB\fR, \fB\fR\f(CBd\fR\fB\fR, \fB\fR\f(CBl\fR\fB\fR, and \fB\fR\f(CBu\fR\fB\fR" 4
471 .IX Xref " a d l u"
472 .IX Item "a, d, l, and u"
473 These modifiers, all new in 5.14, affect which character\-set rules
474 (Unicode, \fIetc\fR.) are used, as described below in
475 "Character set modifiers".
476 .ie n .IP "\fR\fB""n""\fR\fB\fR" 4
477 .el .IP \fR\f(CBn\fR\fB\fR 4
478 .IX Xref " n regex, non-capture regexp, non-capture regular expression, non-capture"
479 .IX Item "n"
480 Prevent the grouping metacharacters \f(CW\*(C`()\*(C'\fR from capturing. This modifier,
481 new in 5.22, will stop \f(CW$1\fR, \f(CW$2\fR, \fIetc\fR... from being filled in.
482 .Sp
483 .Vb 2
484 \& "hello" =~ /(hi|hello)/; # $1 is "hello"
485 \& "hello" =~ /(hi|hello)/n; # $1 is undef
486 .Ve
487 .Sp
488 This is equivalent to putting \f(CW\*(C`?:\*(C'\fR at the beginning of every capturing group:
489 .Sp
490 .Vb 1
491 \& "hello" =~ /(?:hi|hello)/; # $1 is undef
492 .Ve
493 .Sp
494 \&\f(CW\*(C`/n\*(C'\fR can be negated on a per\-group basis. Alternatively, named captures
495 may still be used.
496 .Sp
497 .Vb 3
498 \& "hello" =~ /(?\-n:(hi|hello))/n; # $1 is "hello"
499 \& "hello" =~ /(?<greet>hi|hello)/n; # $1 is "hello", $+{greet} is
500 \& # "hello"
501 .Ve
502 .IP "Other Modifiers" 4
503 .IX Item "Other Modifiers"
504 There are a number of flags that can be found at the end of regular
505 expression constructs that are \fInot\fR generic regular expression flags, but
506 apply to the operation being performed, like matching or substitution (\f(CW\*(C`m//\*(C'\fR
507 or \f(CW\*(C`s///\*(C'\fR respectively).
508 .Sp
509 Flags described further in
510 "Using regular expressions in Perl" in perlretut are:
511 .Sp
512 .Vb 2
513 \& c \- keep the current position during repeated matching
514 \& g \- globally match the pattern repeatedly in the string
515 .Ve
516 .Sp
517 Substitution\-specific modifiers described in
518 "s/PATTERN/REPLACEMENT/msixpodualngcer" in perlop are:
519 .Sp
520 .Vb 4
521 \& e \- evaluate the right\-hand side as an expression
522 \& ee \- evaluate the right side as a string then eval the result
523 \& o \- pretend to optimize your code, but actually introduce bugs
524 \& r \- perform non\-destructive substitution and return the new value
525 .Ve
526 .PP
527 Regular expression modifiers are usually written in documentation
528 as \fIe.g.\fR, "the \f(CW\*(C`/x\*(C'\fR modifier", even though the delimiter
529 in question might not really be a slash. The modifiers \f(CW\*(C`/imnsxadlup\*(C'\fR
530 may also be embedded within the regular expression itself using
531 the \f(CW\*(C`(?...)\*(C'\fR construct, see "Extended Patterns" below.
532 .PP
533 \fIDetails on some modifiers\fR
534 .IX Subsection "Details on some modifiers"
535 .PP
536 Some of the modifiers require more explanation than given in the
537 "Overview" above.
538 .PP
539 \f(CW\*(C`/x\*(C'\fR and \f(CW\*(C`/xx\*(C'\fR
540 .IX Subsection "/x and /xx"
541 .PP
542 A single \f(CW\*(C`/x\*(C'\fR tells
543 the regular expression parser to ignore most whitespace that is neither
544 backslashed nor within a bracketed character class, nor within the characters
545 of a multi\-character metapattern like \f(CW\*(C`(?i: ... )\*(C'\fR. You can use this to
546 break up your regular expression into more readable parts.
547 Also, the \f(CW"#"\fR character is treated as a metacharacter introducing a
548 comment that runs up to the pattern\*(Aqs closing delimiter, or to the end
549 of the current line if the pattern extends onto the next line. Hence,
550 this is very much like an ordinary Perl code comment. (You can include
551 the closing delimiter within the comment only if you precede it with a
552 backslash, so be careful!)
553 .PP
554 Use of \f(CW\*(C`/x\*(C'\fR means that if you want real
555 whitespace or \f(CW"#"\fR characters in the pattern (outside a bracketed character
556 class, which is unaffected by \f(CW\*(C`/x\*(C'\fR), then you\*(Aqll either have to
557 escape them (using backslashes or \f(CW\*(C`\eQ...\eE\*(C'\fR) or encode them using octal,
558 hex, or \f(CW\*(C`\eN{}\*(C'\fR or \f(CW\*(C`\ep{name=...}\*(C'\fR escapes.
559 It is ineffective to try to continue a comment onto the next line by
560 escaping the \f(CW\*(C`\en\*(C'\fR with a backslash or \f(CW\*(C`\eQ\*(C'\fR.
561 .PP
562 You can use "(?#text)" to create a comment that ends earlier than the
563 end of the current line, but \f(CW\*(C`text\*(C'\fR also can\*(Aqt contain the closing
564 delimiter unless escaped with a backslash.
565 .PP
566 A common pitfall is to forget that \f(CW"#"\fR characters (outside a
567 bracketed character class) begin a comment under \f(CW\*(C`/x\*(C'\fR and are not
568 matched literally. Just keep that in mind when trying to puzzle out why
569 a particular \f(CW\*(C`/x\*(C'\fR pattern isn\*(Aqt working as expected.
570 Inside a bracketed character class, \f(CW"#"\fR retains its non\-special,
571 literal meaning.
572 .PP
573 Starting in Perl v5.26, if the modifier has a second \f(CW"x"\fR within it,
574 the effect of a single \f(CW\*(C`/x\*(C'\fR is increased. The only difference is that
575 inside bracketed character classes, non\-escaped (by a backslash) SPACE
576 and TAB characters are not added to the class, and hence can be inserted
577 to make the classes more readable:
578 .PP
579 .Vb 2
580 \& / [d\-e g\-i 3\-7]/xx
581 \& /[ ! @ " # $ % ^ & * () = ? <> \*(Aq ]/xx
582 .Ve
583 .PP
584 may be easier to grasp than the squashed equivalents
585 .PP
586 .Vb 2
587 \& /[d\-eg\-i3\-7]/
588 \& /[!@"#$%^&*()=?<>\*(Aq]/
589 .Ve
590 .PP
591 Note that this unfortunately doesn\*(Aqt mean that your bracketed classes
592 can contain comments or extend over multiple lines. A \f(CW\*(C`#\*(C'\fR inside a
593 character class is still just a literal \f(CW\*(C`#\*(C'\fR, and doesn\*(Aqt introduce a
594 comment. And, unless the closing bracket is on the same line as the
595 opening one, the newline character (and everything on the next line(s)
596 until terminated by a \f(CW\*(C`]\*(C'\fR will be part of the class, just as if you\*(Aqd
597 written \f(CW\*(C`\en\*(C'\fR.
598 .PP
599 Taken together, these features go a long way towards
600 making Perl\*(Aqs regular expressions more readable. Here\*(Aqs an example:
601 .PP
602 .Vb 6
603 \& # Delete (most) C comments.
604 \& $program =~ s {
605 \& /\e* # Match the opening delimiter.
606 \& .*? # Match a minimal number of characters.
607 \& \e*/ # Match the closing delimiter.
608 \& } []gsx;
609 .Ve
610 .PP
611 Note that anything inside
612 a \f(CW\*(C`\eQ...\eE\*(C'\fR stays unaffected by \f(CW\*(C`/x\*(C'\fR. And note that \f(CW\*(C`/x\*(C'\fR doesn\*(Aqt affect
613 space interpretation within a single multi\-character construct. For
614 example \f(CW\*(C`(?:...)\*(C'\fR can\*(Aqt have a space between the \f(CW"("\fR,
615 \&\f(CW"?"\fR, and \f(CW":"\fR. Within any delimiters for such a construct, allowed
616 spaces are not affected by \f(CW\*(C`/x\*(C'\fR, and depend on the construct. For
617 example, all constructs using curly braces as delimiters, such as
618 \&\f(CW\*(C`\ex{...}\*(C'\fR can have blanks within but adjacent to the braces, but not
619 elsewhere, and no non\-blank space characters. An exception are Unicode
620 properties which follow Unicode rules, for which see
621 "Properties accessible through \ep{} and \eP{}" in perluniprops.
622 .IX Xref " x"
623 .PP
624 The set of characters that are deemed whitespace are those that Unicode
625 calls "Pattern White Space", namely:
626 .PP
627 .Vb 11
628 \& U+0009 CHARACTER TABULATION
629 \& U+000A LINE FEED
630 \& U+000B LINE TABULATION
631 \& U+000C FORM FEED
632 \& U+000D CARRIAGE RETURN
633 \& U+0020 SPACE
634 \& U+0085 NEXT LINE
635 \& U+200E LEFT\-TO\-RIGHT MARK
636 \& U+200F RIGHT\-TO\-LEFT MARK
637 \& U+2028 LINE SEPARATOR
638 \& U+2029 PARAGRAPH SEPARATOR
639 .Ve
640 .PP
641 Character set modifiers
642 .IX Subsection "Character set modifiers"
643 .PP
644 \&\f(CW\*(C`/d\*(C'\fR, \f(CW\*(C`/u\*(C'\fR, \f(CW\*(C`/a\*(C'\fR, and \f(CW\*(C`/l\*(C'\fR, available starting in 5.14, are called
645 the character set modifiers; they affect the character set rules
646 used for the regular expression.
647 .PP
648 The \f(CW\*(C`/d\*(C'\fR, \f(CW\*(C`/u\*(C'\fR, and \f(CW\*(C`/l\*(C'\fR modifiers are not likely to be of much use
649 to you, and so you need not worry about them very much. They exist for
650 Perl\*(Aqs internal use, so that complex regular expression data structures
651 can be automatically serialized and later exactly reconstituted,
652 including all their nuances. But, since Perl can\*(Aqt keep a secret, and
653 there may be rare instances where they are useful, they are documented
654 here.
655 .PP
656 The \f(CW\*(C`/a\*(C'\fR modifier, on the other hand, may be useful. Its purpose is to
657 allow code that is to work mostly on ASCII data to not have to concern
658 itself with Unicode.
659 .PP
660 Briefly, \f(CW\*(C`/l\*(C'\fR sets the character set to that of whatever \fBL\fRocale is in
661 effect at the time of the execution of the pattern match.
662 .PP
663 \&\f(CW\*(C`/u\*(C'\fR sets the character set to \fBU\fRnicode.
664 .PP
665 \&\f(CW\*(C`/a\*(C'\fR also sets the character set to Unicode, BUT adds several
666 restrictions for \fBA\fRSCII\-safe matching.
667 .PP
668 \&\f(CW\*(C`/d\*(C'\fR is the old, problematic, pre\-5.14 \fBD\fRefault character set
669 behavior. Its only use is to force that old behavior.
670 .PP
671 At any given time, exactly one of these modifiers is in effect. Their
672 existence allows Perl to keep the originally compiled behavior of a
673 regular expression, regardless of what rules are in effect when it is
674 actually executed. And if it is interpolated into a larger regex, the
675 original\*(Aqs rules continue to apply to it, and don\*(Aqt affect the other
676 parts.
677 .PP
678 The \f(CW\*(C`/l\*(C'\fR and \f(CW\*(C`/u\*(C'\fR modifiers are automatically selected for
679 regular expressions compiled within the scope of various pragmas,
680 and we recommend that in general, you use those pragmas instead of
681 specifying these modifiers explicitly. For one thing, the modifiers
682 affect only pattern matching, and do not extend to even any replacement
683 done, whereas using the pragmas gives consistent results for all
684 appropriate operations within their scopes. For example,
685 .PP
686 .Vb 1
687 \& s/foo/\eUbar/il
688 .Ve
689 .PP
690 will match "foo" using the locale\*(Aqs rules for case\-insensitive matching,
691 but the \f(CW\*(C`/l\*(C'\fR does not affect how the \f(CW\*(C`\eU\*(C'\fR operates. Most likely you
692 want both of them to use locale rules. To do this, instead compile the
693 regular expression within the scope of \f(CW\*(C`use locale\*(C'\fR. This both
694 implicitly adds the \f(CW\*(C`/l\*(C'\fR, and applies locale rules to the \f(CW\*(C`\eU\*(C'\fR. The
695 lesson is to \f(CW\*(C`use locale\*(C'\fR, and not \f(CW\*(C`/l\*(C'\fR explicitly.
696 .PP
697 Similarly, it would be better to use \f(CW\*(C`use feature \*(Aqunicode_strings\*(Aq\*(C'\fR
698 instead of,
699 .PP
700 .Vb 1
701 \& s/foo/\eLbar/iu
702 .Ve
703 .PP
704 to get Unicode rules, as the \f(CW\*(C`\eL\*(C'\fR in the former (but not necessarily
705 the latter) would also use Unicode rules.
706 .PP
707 More detail on each of the modifiers follows. Most likely you don\*(Aqt
708 need to know this detail for \f(CW\*(C`/l\*(C'\fR, \f(CW\*(C`/u\*(C'\fR, and \f(CW\*(C`/d\*(C'\fR, and can skip ahead
709 to /a.
710 .PP
711 /l
712 .IX Subsection "/l"
713 .PP
714 means to use the current locale\*(Aqs rules (see perllocale) when pattern
715 matching. For example, \f(CW\*(C`\ew\*(C'\fR will match the "word" characters of that
716 locale, and \f(CW"/i"\fR case\-insensitive matching will match according to
717 the locale\*(Aqs case folding rules. The locale used will be the one in
718 effect at the time of execution of the pattern match. This may not be
719 the same as the compilation\-time locale, and can differ from one match
720 to another if there is an intervening call of the
721 \&\fBsetlocale()\fR function.
722 .PP
723 Prior to v5.20, Perl did not support multi\-byte locales. Starting then,
724 UTF\-8 locales are supported. No other multi byte locales are ever
725 likely to be supported. However, in all locales, one can have code
726 points above 255 and these will always be treated as Unicode no matter
727 what locale is in effect.
728 .PP
729 Under Unicode rules, there are a few case\-insensitive matches that cross
730 the 255/256 boundary. Except for UTF\-8 locales in Perls v5.20 and
731 later, these are disallowed under \f(CW\*(C`/l\*(C'\fR. For example, 0xFF (on ASCII
732 platforms) does not caselessly match the character at 0x178, \f(CW\*(C`LATIN
733 CAPITAL LETTER Y WITH DIAERESIS\*(C'\fR, because 0xFF may not be \f(CW\*(C`LATIN SMALL
734 LETTER Y WITH DIAERESIS\*(C'\fR in the current locale, and Perl has no way of
735 knowing if that character even exists in the locale, much less what code
736 point it is.
737 .PP
738 In a UTF\-8 locale in v5.20 and later, the only visible difference
739 between locale and non\-locale in regular expressions should be tainting,
740 if your perl supports taint checking (see perlsec).
741 .PP
742 This modifier may be specified to be the default by \f(CW\*(C`use locale\*(C'\fR, but
743 see "Which character set modifier is in effect?".
744 .IX Xref " l"
745 .PP
746 /u
747 .IX Subsection "/u"
748 .PP
749 means to use Unicode rules when pattern matching. On ASCII platforms,
750 this means that the code points between 128 and 255 take on their
751 Latin\-1 (ISO\-8859\-1) meanings (which are the same as Unicode\*(Aqs).
752 (Otherwise Perl considers their meanings to be undefined.) Thus,
753 under this modifier, the ASCII platform effectively becomes a Unicode
754 platform; and hence, for example, \f(CW\*(C`\ew\*(C'\fR will match any of the more than
755 100_000 word characters in Unicode.
756 .PP
757 Unlike most locales, which are specific to a language and country pair,
758 Unicode classifies all the characters that are letters \fIsomewhere\fR in
759 the world as
760 \&\f(CW\*(C`\ew\*(C'\fR. For example, your locale might not think that \f(CW\*(C`LATIN SMALL
761 LETTER ETH\*(C'\fR is a letter (unless you happen to speak Icelandic), but
762 Unicode does. Similarly, all the characters that are decimal digits
763 somewhere in the world will match \f(CW\*(C`\ed\*(C'\fR; this is hundreds, not 10,
764 possible matches. And some of those digits look like some of the 10
765 ASCII digits, but mean a different number, so a human could easily think
766 a number is a different quantity than it really is. For example,
767 \&\f(CW\*(C`BENGALI DIGIT FOUR\*(C'\fR (U+09EA) looks very much like an
768 \&\f(CW\*(C`ASCII DIGIT EIGHT\*(C'\fR (U+0038), and \f(CW\*(C`LEPCHA DIGIT SIX\*(C'\fR (U+1C46) looks
769 very much like an \f(CW\*(C`ASCII DIGIT FIVE\*(C'\fR (U+0035). And, \f(CW\*(C`\ed+\*(C'\fR, may match
770 strings of digits that are a mixture from different writing systems,
771 creating a security issue. A fraudulent website, for example, could
772 display the price of something using U+1C46, and it would appear to the
773 user that something cost 500 units, but it really costs 600. A browser
774 that enforced script runs ("Script Runs") would prevent that
775 fraudulent display. "\fBnum()\fR" in Unicode::UCD can also be used to sort this
776 out. Or the \f(CW\*(C`/a\*(C'\fR modifier can be used to force \f(CW\*(C`\ed\*(C'\fR to match just the
777 ASCII 0 through 9.
778 .PP
779 Also, under this modifier, case\-insensitive matching works on the full
780 set of Unicode
781 characters. The \f(CW\*(C`KELVIN SIGN\*(C'\fR, for example matches the letters "k" and
782 "K"; and \f(CW\*(C`LATIN SMALL LIGATURE FF\*(C'\fR matches the sequence "ff", which,
783 if you\*(Aqre not prepared, might make it look like a hexadecimal constant,
784 presenting another potential security issue. See
785 <https://unicode.org/reports/tr36> for a detailed discussion of Unicode
786 security issues.
787 .PP
788 This modifier may be specified to be the default by \f(CW\*(C`use feature
789 \&\*(Aqunicode_strings\*(C'\fR, \f(CW\*(C`use locale \*(Aq:not_characters\*(Aq\*(C'\fR, or
790 \&\f(CW\*(C`use v5.12\*(C'\fR (or higher),
791 but see "Which character set modifier is in effect?".
792 .IX Xref " u"
793 .PP
794 /d
795 .IX Subsection "/d"
796 .PP
797 \&\fBIMPORTANT:\fR Because of the unpredictable behaviors this
798 modifier causes, only use it to maintain weird backward compatibilities.
799 Use the
800 \&\f(CW\*(C`unicode_strings\*(C'\fR
801 feature
802 in new code to avoid inadvertently enabling this modifier by default.
803 .PP
804 What does this modifier do? It "Depends"!
805 .PP
806 This modifier means to use platform\-native matching rules
807 except when there is cause to use Unicode rules instead, as follows:
808 .IP 1. 4
809 the target string\*(Aqs UTF8 flag
810 (see below) is set; or
811 .IP 2. 4
812 the pattern\*(Aqs UTF8 flag
813 (see below) is set; or
814 .IP 3. 4
815 the pattern explicitly mentions a code point that is above 255 (say by
816 \&\f(CW\*(C`\ex{100}\*(C'\fR); or
817 .IP 4. 4
818 the pattern uses a Unicode name (\f(CW\*(C`\eN{...}\*(C'\fR); or
819 .IP 5. 4
820 the pattern uses a Unicode property (\f(CW\*(C`\ep{...}\*(C'\fR or \f(CW\*(C`\eP{...}\*(C'\fR); or
821 .IP 6. 4
822 the pattern uses a Unicode break (\f(CW\*(C`\eb{...}\*(C'\fR or \f(CW\*(C`\eB{...}\*(C'\fR); or
823 .IP 7. 4
824 the pattern uses \f(CW"(?[ ])"\fR
825 .IP 8. 4
826 the pattern uses \f(CW\*(C`(*script_run: ...)\*(C'\fR
827 .PP
828 Regarding the "UTF8 flag" references above: normally Perl applications
829 shouldn\*(Aqt think about that flag. It\*(Aqs part of Perl\*(Aqs internals,
830 so it can change whenever Perl wants. \f(CW\*(C`/d\*(C'\fR may thus cause unpredictable
831 results. See "The "Unicode Bug"" in perlunicode. This bug
832 has become rather infamous, leading to yet other (without swearing) names
833 for this modifier like "Dicey" and "Dodgy".
834 .PP
835 Here are some examples of how that works on an ASCII platform:
836 .PP
837 .Vb 3
838 \& $str = "\exDF"; #
839 \& utf8::downgrade($str); # $str is not UTF8\-flagged.
840 \& $str =~ /^\ew/; # No match, since no UTF8 flag.
841 \&
842 \& $str .= "\ex{0e0b}"; # Now $str is UTF8\-flagged.
843 \& $str =~ /^\ew/; # Match! $str is now UTF8\-flagged.
844 \& chop $str;
845 \& $str =~ /^\ew/; # Still a match! $str retains its UTF8 flag.
846 .Ve
847 .PP
848 Under Perl\*(Aqs default configuration this modifier is automatically
849 selected by default when none of the others are, so yet another name
850 for it (unfortunately) is "Default".
851 .PP
852 Whenever you can, use the
853 \&\f(CW\*(C`unicode_strings\*(C'\fR
854 to cause \f(CW\*(C`/u\*(C'\fR to be the default instead.
855 .PP
856 /a (and /aa)
857 .IX Subsection "/a (and /aa)"
858 .PP
859 This modifier stands for ASCII\-restrict (or ASCII\-safe). This modifier
860 may be doubled\-up to increase its effect.
861 .PP
862 When it appears singly, it causes the sequences \f(CW\*(C`\ed\*(C'\fR, \f(CW\*(C`\es\*(C'\fR, \f(CW\*(C`\ew\*(C'\fR, and
863 the Posix character classes to match only in the ASCII range. They thus
864 revert to their pre\-5.6, pre\-Unicode meanings. Under \f(CW\*(C`/a\*(C'\fR, \f(CW\*(C`\ed\*(C'\fR
865 always means precisely the digits \f(CW"0"\fR to \f(CW"9"\fR; \f(CW\*(C`\es\*(C'\fR means the five
866 characters \f(CW\*(C`[ \ef\en\er\et]\*(C'\fR, and starting in Perl v5.18, the vertical tab;
867 \&\f(CW\*(C`\ew\*(C'\fR means the 63 characters
868 \&\f(CW\*(C`[A\-Za\-z0\-9_]\*(C'\fR; and likewise, all the Posix classes such as
869 \&\f(CW\*(C`[[:print:]]\*(C'\fR match only the appropriate ASCII\-range characters.
870 .PP
871 This modifier is useful for people who only incidentally use Unicode,
872 and who do not wish to be burdened with its complexities and security
873 concerns.
874 .PP
875 With \f(CW\*(C`/a\*(C'\fR, one can write \f(CW\*(C`\ed\*(C'\fR with confidence that it will only match
876 ASCII characters, and should the need arise to match beyond ASCII, you
877 can instead use \f(CW\*(C`\ep{Digit}\*(C'\fR (or \f(CW\*(C`\ep{Word}\*(C'\fR for \f(CW\*(C`\ew\*(C'\fR). There are
878 similar \f(CW\*(C`\ep{...}\*(C'\fR constructs that can match beyond ASCII both white
879 space (see "Whitespace" in perlrecharclass), and Posix classes (see
880 "POSIX Character Classes" in perlrecharclass). Thus, this modifier
881 doesn\*(Aqt mean you can\*(Aqt use Unicode, it means that to get Unicode
882 matching you must explicitly use a construct (\f(CW\*(C`\ep{}\*(C'\fR, \f(CW\*(C`\eP{}\*(C'\fR) that
883 signals Unicode.
884 .PP
885 As you would expect, this modifier causes, for example, \f(CW\*(C`\eD\*(C'\fR to mean
886 the same thing as \f(CW\*(C`[^0\-9]\*(C'\fR; in fact, all non\-ASCII characters match
887 \&\f(CW\*(C`\eD\*(C'\fR, \f(CW\*(C`\eS\*(C'\fR, and \f(CW\*(C`\eW\*(C'\fR. \f(CW\*(C`\eb\*(C'\fR still means to match at the boundary
888 between \f(CW\*(C`\ew\*(C'\fR and \f(CW\*(C`\eW\*(C'\fR, using the \f(CW\*(C`/a\*(C'\fR definitions of them (similarly
889 for \f(CW\*(C`\eB\*(C'\fR).
890 .PP
891 Otherwise, \f(CW\*(C`/a\*(C'\fR behaves like the \f(CW\*(C`/u\*(C'\fR modifier, in that
892 case\-insensitive matching uses Unicode rules; for example, "k" will
893 match the Unicode \f(CW\*(C`\eN{KELVIN SIGN}\*(C'\fR under \f(CW\*(C`/i\*(C'\fR matching, and code
894 points in the Latin1 range, above ASCII will have Unicode rules when it
895 comes to case\-insensitive matching.
896 .PP
897 To forbid ASCII/non\-ASCII matches (like "k" with \f(CW\*(C`\eN{KELVIN SIGN}\*(C'\fR),
898 specify the \f(CW"a"\fR twice, for example \f(CW\*(C`/aai\*(C'\fR or \f(CW\*(C`/aia\*(C'\fR. (The first
899 occurrence of \f(CW"a"\fR restricts the \f(CW\*(C`\ed\*(C'\fR, \fIetc\fR., and the second occurrence
900 adds the \f(CW\*(C`/i\*(C'\fR restrictions.) But, note that code points outside the
901 ASCII range will use Unicode rules for \f(CW\*(C`/i\*(C'\fR matching, so the modifier
902 doesn\*(Aqt really restrict things to just ASCII; it just forbids the
903 intermixing of ASCII and non\-ASCII.
904 .PP
905 To summarize, this modifier provides protection for applications that
906 don\*(Aqt wish to be exposed to all of Unicode. Specifying it twice
907 gives added protection.
908 .PP
909 This modifier may be specified to be the default by \f(CW\*(C`use re \*(Aq/a\*(Aq\*(C'\fR
910 or \f(CW\*(C`use re \*(Aq/aa\*(Aq\*(C'\fR. If you do so, you may actually have occasion to use
911 the \f(CW\*(C`/u\*(C'\fR modifier explicitly if there are a few regular expressions
912 where you do want full Unicode rules (but even here, it\*(Aqs best if
913 everything were under feature \f(CW"unicode_strings"\fR, along with the
914 \&\f(CW\*(C`use re \*(Aq/aa\*(Aq\*(C'\fR). Also see "Which character set modifier is in
915 effect?".
916 .IX Xref " a aa"
917 .PP
918 Which character set modifier is in effect?
919 .IX Subsection "Which character set modifier is in effect?"
920 .PP
921 Which of these modifiers is in effect at any given point in a regular
922 expression depends on a fairly complex set of interactions. These have
923 been designed so that in general you don\*(Aqt have to worry about it, but
924 this section gives the gory details. As
925 explained below in "Extended Patterns" it is possible to explicitly
926 specify modifiers that apply only to portions of a regular expression.
927 The innermost always has priority over any outer ones, and one applying
928 to the whole expression has priority over any of the default settings that are
929 described in the remainder of this section.
930 .PP
931 The \f(CW\*(C`use re \*(Aq/foo\*(Aq\*(C'\fR pragma can be used to set
932 default modifiers (including these) for regular expressions compiled
933 within its scope. This pragma has precedence over the other pragmas
934 listed below that also change the defaults. Note that the /x modifier does
935 NOT affect \f(CW\*(C`split STR\*(C'\fR patterns.
936 .PP
937 Otherwise, \f(CW\*(C`use locale\*(C'\fR sets the default modifier to \f(CW\*(C`/l\*(C'\fR;
938 and \f(CW\*(C`use feature \*(Aqunicode_strings\*(C'\fR, or
939 \&\f(CW\*(C`use v5.12\*(C'\fR (or higher) set the default to
940 \&\f(CW\*(C`/u\*(C'\fR when not in the same scope as either \f(CW\*(C`use locale\*(C'\fR
941 or \f(CW\*(C`use bytes\*(C'\fR.
942 (\f(CW\*(C`use locale \*(Aq:not_characters\*(Aq\*(C'\fR also
943 sets the default to \f(CW\*(C`/u\*(C'\fR, overriding any plain \f(CW\*(C`use locale\*(C'\fR.)
944 Unlike the mechanisms mentioned above, these
945 affect operations besides regular expressions pattern matching, and so
946 give more consistent results with other operators, including using
947 \&\f(CW\*(C`\eU\*(C'\fR, \f(CW\*(C`\el\*(C'\fR, \fIetc\fR. in substitution replacements.
948 .PP
949 If none of the above apply, for backwards compatibility reasons, the
950 \&\f(CW\*(C`/d\*(C'\fR modifier is the one in effect by default. As this can lead to
951 unexpected results, it is best to specify which other rule set should be
952 used.
953 .PP
954 Character set modifier behavior prior to Perl 5.14
955 .IX Subsection "Character set modifier behavior prior to Perl 5.14"
956 .PP
957 Prior to 5.14, there were no explicit modifiers, but \f(CW\*(C`/l\*(C'\fR was implied
958 for regexes compiled within the scope of \f(CW\*(C`use locale\*(C'\fR, and \f(CW\*(C`/d\*(C'\fR was
959 implied otherwise. However, interpolating a regex into a larger regex
960 would ignore the original compilation in favor of whatever was in effect
961 at the time of the second compilation. There were a number of
962 inconsistencies (bugs) with the \f(CW\*(C`/d\*(C'\fR modifier, where Unicode rules
963 would be used when inappropriate, and vice versa. \f(CW\*(C`\ep{}\*(C'\fR did not imply
964 Unicode rules, and neither did all occurrences of \f(CW\*(C`\eN{}\*(C'\fR, until 5.12.
965 .SS "Regular Expressions"
966 .IX Subsection "Regular Expressions"
967 \fIQuantifiers\fR
968 .IX Subsection "Quantifiers"
969 .PP
970 Quantifiers are used when a particular portion of a pattern needs to
971 match a certain number (or numbers) of times. If there isn\*(Aqt a
972 quantifier the number of times to match is exactly one. The following
973 standard quantifiers are recognized:
974 .IX Xref "metacharacter quantifier * + ? {n} {n,} {n,m}"
975 .PP
976 .Vb 7
977 \& * Match 0 or more times
978 \& + Match 1 or more times
979 \& ? Match 1 or 0 times
980 \& {n} Match exactly n times
981 \& {n,} Match at least n times
982 \& {,n} Match at most n times
983 \& {n,m} Match at least n but not more than m times
984 .Ve
985 .PP
986 (If a non\-escaped curly bracket occurs in a context other than one of
987 the quantifiers listed above, where it does not form part of a
988 backslashed sequence like \f(CW\*(C`\ex{...}\*(C'\fR, it is either a fatal syntax error,
989 or treated as a regular character, generally with a deprecation warning
990 raised. To escape it, you can precede it with a backslash (\f(CW"\e{"\fR) or
991 enclose it within square brackets (\f(CW"[{]"\fR).
992 This change will allow for future syntax extensions (like making the
993 lower bound of a quantifier optional), and better error checking of
994 quantifiers).
995 .PP
996 The \f(CW"*"\fR quantifier is equivalent to \f(CW\*(C`{0,}\*(C'\fR, the \f(CW"+"\fR
997 quantifier to \f(CW\*(C`{1,}\*(C'\fR, and the \f(CW"?"\fR quantifier to \f(CW\*(C`{0,1}\*(C'\fR. \fIn\fR and \fIm\fR are limited
998 to non\-negative integral values less than a preset limit defined when perl is built.
999 This is usually 65534 on the most common platforms. The actual limit can
1000 be seen in the error message generated by code such as this:
1001 .PP
1002 .Vb 1
1003 \& $_ **= $_ , / {$_} / for 2 .. 42;
1004 .Ve
1005 .PP
1006 By default, a quantified subpattern is "greedy", that is, it will match as
1007 many times as possible (given a particular starting location) while still
1008 allowing the rest of the pattern to match. If you want it to match the
1009 minimum number of times possible, follow the quantifier with a \f(CW"?"\fR. Note
1010 that the meanings don\*(Aqt change, just the "greediness":
1011 .IX Xref "metacharacter greedy greediness ? *? +? ?? {n}? {n,}? {,n}? {n,m}?"
1012 .PP
1013 .Vb 7
1014 \& *? Match 0 or more times, not greedily
1015 \& +? Match 1 or more times, not greedily
1016 \& ?? Match 0 or 1 time, not greedily
1017 \& {n}? Match exactly n times, not greedily (redundant)
1018 \& {n,}? Match at least n times, not greedily
1019 \& {,n}? Match at most n times, not greedily
1020 \& {n,m}? Match at least n but not more than m times, not greedily
1021 .Ve
1022 .PP
1023 Normally when a quantified subpattern does not allow the rest of the
1024 overall pattern to match, Perl will backtrack. However, this behaviour is
1025 sometimes undesirable. Thus Perl provides the "possessive" quantifier form
1026 as well.
1027 .PP
1028 .Vb 7
1029 \& *+ Match 0 or more times and give nothing back
1030 \& ++ Match 1 or more times and give nothing back
1031 \& ?+ Match 0 or 1 time and give nothing back
1032 \& {n}+ Match exactly n times and give nothing back (redundant)
1033 \& {n,}+ Match at least n times and give nothing back
1034 \& {,n}+ Match at most n times and give nothing back
1035 \& {n,m}+ Match at least n but not more than m times and give nothing back
1036 .Ve
1037 .PP
1038 For instance,
1039 .PP
1040 .Vb 1
1041 \& \*(Aqaaaa\*(Aq =~ /a++a/
1042 .Ve
1043 .PP
1044 will never match, as the \f(CW\*(C`a++\*(C'\fR will gobble up all the \f(CW"a"\fR\*(Aqs in the
1045 string and won\*(Aqt leave any for the remaining part of the pattern. This
1046 feature can be extremely useful to give perl hints about where it
1047 shouldn\*(Aqt backtrack. For instance, the typical "match a double\-quoted
1048 string" problem can be most efficiently performed when written as:
1049 .PP
1050 .Vb 1
1051 \& /"(?:[^"\e\e]++|\e\e.)*+"/
1052 .Ve
1053 .PP
1054 as we know that if the final quote does not match, backtracking will not
1055 help. See the independent subexpression
1056 \&\f(CW"(?>\fR\f(CIpattern\fR\f(CW)"\fR for more details;
1057 possessive quantifiers are just syntactic sugar for that construct. For
1058 instance the above example could also be written as follows:
1059 .PP
1060 .Vb 1
1061 \& /"(?>(?:(?>[^"\e\e]+)|\e\e.)*)"/
1062 .Ve
1063 .PP
1064 Note that the possessive quantifier modifier can not be combined
1065 with the non\-greedy modifier. This is because it would make no sense.
1066 Consider the follow equivalency table:
1067 .PP
1068 .Vb 5
1069 \& Illegal Legal
1070 \& \-\-\-\-\-\-\-\-\-\-\-\- \-\-\-\-\-\-
1071 \& X??+ X{0}
1072 \& X+?+ X{1}
1073 \& X{min,max}?+ X{min}
1074 .Ve
1075 .PP
1076 \fIEscape sequences\fR
1077 .IX Subsection "Escape sequences"
1078 .PP
1079 Because patterns are processed as double\-quoted strings, the following
1080 also work:
1081 .PP
1082 .Vb 10
1083 \& \et tab (HT, TAB)
1084 \& \en newline (LF, NL)
1085 \& \er return (CR)
1086 \& \ef form feed (FF)
1087 \& \ea alarm (bell) (BEL)
1088 \& \ee escape (think troff) (ESC)
1089 \& \ecK control char (example: VT)
1090 \& \ex{}, \ex00 character whose ordinal is the given hexadecimal number
1091 \& \eN{name} named Unicode character or character sequence
1092 \& \eN{U+263D} Unicode character (example: FIRST QUARTER MOON)
1093 \& \eo{}, \e000 character whose ordinal is the given octal number
1094 \& \el lowercase next char (think vi)
1095 \& \eu uppercase next char (think vi)
1096 \& \eL lowercase until \eE (think vi)
1097 \& \eU uppercase until \eE (think vi)
1098 \& \eQ quote (disable) pattern metacharacters until \eE
1099 \& \eE end either case modification or quoted section, think vi
1100 .Ve
1101 .PP
1102 Details are in "Quote and Quote\-like Operators" in perlop.
1103 .PP
1104 \fICharacter Classes and other Special Escapes\fR
1105 .IX Subsection "Character Classes and other Special Escapes"
1106 .PP
1107 In addition, Perl defines the following:
1108 .IX Xref "\\g \\k \\K backreference"
1109 .PP
1110 .Vb 10
1111 \& Sequence Note Description
1112 \& [...] [1] Match a character according to the rules of the
1113 \& bracketed character class defined by the "...".
1114 \& Example: [a\-z] matches "a" or "b" or "c" ... or "z"
1115 \& [[:...:]] [2] Match a character according to the rules of the POSIX
1116 \& character class "..." within the outer bracketed
1117 \& character class. Example: [[:upper:]] matches any
1118 \& uppercase character.
1119 \& (?[...]) [8] Extended bracketed character class
1120 \& \ew [3] Match a "word" character (alphanumeric plus "_", plus
1121 \& other connector punctuation chars plus Unicode
1122 \& marks)
1123 \& \eW [3] Match a non\-"word" character
1124 \& \es [3] Match a whitespace character
1125 \& \eS [3] Match a non\-whitespace character
1126 \& \ed [3] Match a decimal digit character
1127 \& \eD [3] Match a non\-digit character
1128 \& \epP [3] Match P, named property. Use \ep{Prop} for longer names
1129 \& \ePP [3] Match non\-P
1130 \& \eX [4] Match Unicode "eXtended grapheme cluster"
1131 \& \e1 [5] Backreference to a specific capture group or buffer.
1132 \& \*(Aq1\*(Aq may actually be any positive integer.
1133 \& \eg1 [5] Backreference to a specific or previous group,
1134 \& \eg{\-1} [5] The number may be negative indicating a relative
1135 \& previous group and may optionally be wrapped in
1136 \& curly brackets for safer parsing.
1137 \& \eg{name} [5] Named backreference
1138 \& \ek<name> [5] Named backreference
1139 \& \ek\*(Aqname\*(Aq [5] Named backreference
1140 \& \ek{name} [5] Named backreference
1141 \& \eK [6] Keep the stuff left of the \eK, don\*(Aqt include it in $&
1142 \& \eN [7] Any character but \en. Not affected by /s modifier
1143 \& \ev [3] Vertical whitespace
1144 \& \eV [3] Not vertical whitespace
1145 \& \eh [3] Horizontal whitespace
1146 \& \eH [3] Not horizontal whitespace
1147 \& \eR [4] Linebreak
1148 .Ve
1149 .IP [1] 4
1150 .IX Item "[1]"
1151 See "Bracketed Character Classes" in perlrecharclass for details.
1152 .IP [2] 4
1153 .IX Item "[2]"
1154 See "POSIX Character Classes" in perlrecharclass for details.
1155 .IP [3] 4
1156 .IX Item "[3]"
1157 See "Unicode Character Properties" in perlunicode for details
1158 .IP [4] 4
1159 .IX Item "[4]"
1160 See "Misc" in perlrebackslash for details.
1161 .IP [5] 4
1162 .IX Item "[5]"
1163 See "Capture groups" below for details.
1164 .IP [6] 4
1165 .IX Item "[6]"
1166 See "Extended Patterns" below for details.
1167 .IP [7] 4
1168 .IX Item "[7]"
1169 Note that \f(CW\*(C`\eN\*(C'\fR has two meanings. When of the form \f(CW\*(C`\eN{\fR\f(CINAME\fR\f(CW}\*(C'\fR, it
1170 matches the character or character sequence whose name is \fINAME\fR; and
1171 similarly
1172 when of the form \f(CW\*(C`\eN{U+\fR\f(CIhex\fR\f(CW}\*(C'\fR, it matches the character whose Unicode
1173 code point is \fIhex\fR. Otherwise it matches any character but \f(CW\*(C`\en\*(C'\fR.
1174 .IP [8] 4
1175 .IX Item "[8]"
1176 See "Extended Bracketed Character Classes" in perlrecharclass for details.
1177 .PP
1178 \fIAssertions\fR
1179 .IX Subsection "Assertions"
1180 .PP
1181 Besides \f(CW"^"\fR and \f(CW"$"\fR, Perl defines the following
1182 zero\-width assertions:
1183 .IX Xref "zero-width assertion assertion regex, zero-width assertion regexp, zero-width assertion regular expression, zero-width assertion \\b \\B \\A \\Z \\z \\G"
1184 .PP
1185 .Vb 9
1186 \& \eb{} Match at Unicode boundary of specified type
1187 \& \eB{} Match where corresponding \eb{} doesn\*(Aqt match
1188 \& \eb Match a \ew\eW or \eW\ew boundary
1189 \& \eB Match except at a \ew\eW or \eW\ew boundary
1190 \& \eA Match only at beginning of string
1191 \& \eZ Match only at end of string, or before newline at the end
1192 \& \ez Match only at end of string
1193 \& \eG Match only at pos() (e.g. at the end\-of\-match position
1194 \& of prior m//g)
1195 .Ve
1196 .PP
1197 A Unicode boundary (\f(CW\*(C`\eb{}\*(C'\fR), available starting in v5.22, is a spot
1198 between two characters, or before the first character in the string, or
1199 after the final character in the string where certain criteria defined
1200 by Unicode are met. See "\eb{}, \eb, \eB{}, \eB" in perlrebackslash for
1201 details.
1202 .PP
1203 A word boundary (\f(CW\*(C`\eb\*(C'\fR) is a spot between two characters
1204 that has a \f(CW\*(C`\ew\*(C'\fR on one side of it and a \f(CW\*(C`\eW\*(C'\fR on the other side
1205 of it (in either order), counting the imaginary characters off the
1206 beginning and end of the string as matching a \f(CW\*(C`\eW\*(C'\fR. (Within
1207 character classes \f(CW\*(C`\eb\*(C'\fR represents backspace rather than a word
1208 boundary, just as it normally does in any double\-quoted string.)
1209 The \f(CW\*(C`\eA\*(C'\fR and \f(CW\*(C`\eZ\*(C'\fR are just like \f(CW"^"\fR and \f(CW"$"\fR, except that they
1210 won\*(Aqt match multiple times when the \f(CW\*(C`/m\*(C'\fR modifier is used, while
1211 \&\f(CW"^"\fR and \f(CW"$"\fR will match at every internal line boundary. To match
1212 the actual end of the string and not ignore an optional trailing
1213 newline, use \f(CW\*(C`\ez\*(C'\fR.
1214 .IX Xref "\\b \\A \\Z \\z m"
1215 .PP
1216 The \f(CW\*(C`\eG\*(C'\fR assertion can be used to chain global matches (using
1217 \&\f(CW\*(C`m//g\*(C'\fR), as described in "Regexp Quote\-Like Operators" in perlop.
1218 It is also useful when writing \f(CW\*(C`lex\*(C'\fR\-like scanners, when you have
1219 several patterns that you want to match against consequent substrings
1220 of your string; see the previous reference. The actual location
1221 where \f(CW\*(C`\eG\*(C'\fR will match can also be influenced by using \f(CWpos()\fR as
1222 an lvalue: see "pos" in perlfunc. Note that the rule for zero\-length
1223 matches (see "Repeated Patterns Matching a Zero\-length Substring")
1224 is modified somewhat, in that contents to the left of \f(CW\*(C`\eG\*(C'\fR are
1225 not counted when determining the length of the match. Thus the following
1226 will not match forever:
1227 .IX Xref "\\G"
1228 .PP
1229 .Vb 5
1230 \& my $string = \*(AqABC\*(Aq;
1231 \& pos($string) = 1;
1232 \& while ($string =~ /(.\eG)/g) {
1233 \& print $1;
1234 \& }
1235 .Ve
1236 .PP
1237 It will print \*(AqA\*(Aq and then terminate, as it considers the match to
1238 be zero\-width, and thus will not match at the same position twice in a
1239 row.
1240 .PP
1241 It is worth noting that \f(CW\*(C`\eG\*(C'\fR improperly used can result in an infinite
1242 loop. Take care when using patterns that include \f(CW\*(C`\eG\*(C'\fR in an alternation.
1243 .PP
1244 Note also that \f(CW\*(C`s///\*(C'\fR will refuse to overwrite part of a substitution
1245 that has already been replaced; so for example this will stop after the
1246 first iteration, rather than iterating its way backwards through the
1247 string:
1248 .PP
1249 .Vb 4
1250 \& $_ = "123456789";
1251 \& pos = 6;
1252 \& s/.(?=.\eG)/X/g;
1253 \& print; # prints 1234X6789, not XXXXX6789
1254 .Ve
1255 .PP
1256 \fICapture groups\fR
1257 .IX Subsection "Capture groups"
1258 .PP
1259 The grouping construct \f(CW\*(C`( ... )\*(C'\fR creates capture groups (also referred to as
1260 capture buffers). To refer to the current contents of a group later on, within
1261 the same pattern, use \f(CW\*(C`\eg1\*(C'\fR (or \f(CW\*(C`\eg{1}\*(C'\fR) for the first, \f(CW\*(C`\eg2\*(C'\fR (or \f(CW\*(C`\eg{2}\*(C'\fR)
1262 for the second, and so on.
1263 This is called a \fIbackreference\fR.
1264
1265
1266
1267
1268
1269
1270
1271
1272 There is no limit to the number of captured substrings that you may use.
1273 Groups are numbered with the leftmost open parenthesis being number 1, \fIetc\fR. If
1274 a group did not match, the associated backreference won\*(Aqt match either. (This
1275 can happen if the group is optional, or in a different branch of an
1276 alternation.)
1277 You can omit the \f(CW"g"\fR, and write \f(CW"\e1"\fR, \fIetc\fR, but there are some issues with
1278 this form, described below.
1279 .IX Xref "regex, capture buffer regexp, capture buffer regex, capture group regexp, capture group regular expression, capture buffer backreference regular expression, capture group backreference \\g{1} \\g{-1} \\g{name} relative backreference named backreference named capture buffer regular expression, named capture buffer named capture group regular expression, named capture group %+ $+{name} \\k<name>"
1280 .PP
1281 You can also refer to capture groups relatively, by using a negative number, so
1282 that \f(CW\*(C`\eg\-1\*(C'\fR and \f(CW\*(C`\eg{\-1}\*(C'\fR both refer to the immediately preceding capture
1283 group, and \f(CW\*(C`\eg\-2\*(C'\fR and \f(CW\*(C`\eg{\-2}\*(C'\fR both refer to the group before it. For
1284 example:
1285 .PP
1286 .Vb 8
1287 \& /
1288 \& (Y) # group 1
1289 \& ( # group 2
1290 \& (X) # group 3
1291 \& \eg{\-1} # backref to group 3
1292 \& \eg{\-3} # backref to group 1
1293 \& )
1294 \& /x
1295 .Ve
1296 .PP
1297 would match the same as \f(CW\*(C`/(Y) ( (X) \eg3 \eg1 )/x\*(C'\fR. This allows you to
1298 interpolate regexes into larger regexes and not have to worry about the
1299 capture groups being renumbered.
1300 .PP
1301 You can dispense with numbers altogether and create named capture groups.
1302 The notation is \f(CW\*(C`(?<\fR\f(CIname\fR\f(CW>...)\*(C'\fR to declare and \f(CW\*(C`\eg{\fR\f(CIname\fR\f(CW}\*(C'\fR to
1303 reference. (To be compatible with .Net regular expressions, \f(CW\*(C`\eg{\fR\f(CIname\fR\f(CW}\*(C'\fR may
1304 also be written as \f(CW\*(C`\ek{\fR\f(CIname\fR\f(CW}\*(C'\fR, \f(CW\*(C`\ek<\fR\f(CIname\fR\f(CW>\*(C'\fR or \f(CW\*(C`\ek\*(Aq\fR\f(CIname\fR\f(CW\*(Aq\*(C'\fR.)
1305 \&\fIname\fR must not begin with a number, nor contain hyphens.
1306 When different groups within the same pattern have the same name, any reference
1307 to that name assumes the leftmost defined group. Named groups count in
1308 absolute and relative numbering, and so can also be referred to by those
1309 numbers.
1310 (It\*(Aqs possible to do things with named capture groups that would otherwise
1311 require \f(CW\*(C`(??{})\*(C'\fR.)
1312 .PP
1313 Capture group contents are dynamically scoped and available to you outside the
1314 pattern until the end of the enclosing block or until the next successful
1315 match in the same scope, whichever comes first.
1316 See "Compound Statements" in perlsyn and
1317 "Scoping Rules of Regex Variables" in perlvar for more details.
1318 .PP
1319 You can access the contents of a capture group by absolute number (using
1320 \&\f(CW"$1"\fR instead of \f(CW"\eg1"\fR, \fIetc\fR); or by name via the \f(CW\*(C`%+\*(C'\fR hash,
1321 using \f(CW"$+{\fR\f(CIname\fR\f(CW}"\fR.
1322 .PP
1323 Braces are required in referring to named capture groups, but are optional for
1324 absolute or relative numbered ones. Braces are safer when creating a regex by
1325 concatenating smaller strings. For example if you have \f(CW\*(C`qr/$x$y/\*(C'\fR, and \f(CW$x\fR
1326 contained \f(CW"\eg1"\fR, and \f(CW$y\fR contained \f(CW"37"\fR, you would get \f(CW\*(C`/\eg137/\*(C'\fR which
1327 is probably not what you intended.
1328 .PP
1329 If you use braces, you may also optionally add any number of blank
1330 (space or tab) characters within but adjacent to the braces, like
1331 \&\f(CW\*(C`\eg{\ \-1\ }\*(C'\fR, or \f(CW\*(C`\ek{\ \fR\f(CIname\fR\f(CW\ }\*(C'\fR.
1332 .PP
1333 The \f(CW\*(C`\eg\*(C'\fR and \f(CW\*(C`\ek\*(C'\fR notations were introduced in Perl 5.10.0. Prior to that
1334 there were no named nor relative numbered capture groups. Absolute numbered
1335 groups were referred to using \f(CW\*(C`\e1\*(C'\fR,
1336 \&\f(CW\*(C`\e2\*(C'\fR, \fIetc\fR., and this notation is still
1337 accepted (and likely always will be). But it leads to some ambiguities if
1338 there are more than 9 capture groups, as \f(CW\*(C`\e10\*(C'\fR could mean either the tenth
1339 capture group, or the character whose ordinal in octal is 010 (a backspace in
1340 ASCII). Perl resolves this ambiguity by interpreting \f(CW\*(C`\e10\*(C'\fR as a backreference
1341 only if at least 10 left parentheses have opened before it. Likewise \f(CW\*(C`\e11\*(C'\fR is
1342 a backreference only if at least 11 left parentheses have opened before it.
1343 And so on. \f(CW\*(C`\e1\*(C'\fR through \f(CW\*(C`\e9\*(C'\fR are always interpreted as backreferences.
1344 There are several examples below that illustrate these perils. You can avoid
1345 the ambiguity by always using \f(CW\*(C`\eg{}\*(C'\fR or \f(CW\*(C`\eg\*(C'\fR if you mean capturing groups;
1346 and for octal constants always using \f(CW\*(C`\eo{}\*(C'\fR, or for \f(CW\*(C`\e077\*(C'\fR and below, using 3
1347 digits padded with leading zeros, since a leading zero implies an octal
1348 constant.
1349 .PP
1350 The \f(CW\*(C`\e\fR\f(CIdigit\fR\f(CW\*(C'\fR notation also works in certain circumstances outside
1351 the pattern. See "Warning on \e1 Instead of \f(CW$1\fR" below for details.
1352 .PP
1353 Examples:
1354 .PP
1355 .Vb 1
1356 \& s/^([^ ]*) *([^ ]*)/$2 $1/; # swap first two words
1357 \&
1358 \& /(.)\eg1/ # find first doubled char
1359 \& and print "\*(Aq$1\*(Aq is the first doubled character\en";
1360 \&
1361 \& /(?<char>.)\ek<char>/ # ... a different way
1362 \& and print "\*(Aq$+{char}\*(Aq is the first doubled character\en";
1363 \&
1364 \& /(?\*(Aqchar\*(Aq.)\eg1/ # ... mix and match
1365 \& and print "\*(Aq$1\*(Aq is the first doubled character\en";
1366 \&
1367 \& if (/Time: (..):(..):(..)/) { # parse out values
1368 \& $hours = $1;
1369 \& $minutes = $2;
1370 \& $seconds = $3;
1371 \& }
1372 \&
1373 \& /(.)(.)(.)(.)(.)(.)(.)(.)(.)\eg10/ # \eg10 is a backreference
1374 \& /(.)(.)(.)(.)(.)(.)(.)(.)(.)\e10/ # \e10 is octal
1375 \& /((.)(.)(.)(.)(.)(.)(.)(.)(.))\e10/ # \e10 is a backreference
1376 \& /((.)(.)(.)(.)(.)(.)(.)(.)(.))\e010/ # \e010 is octal
1377 \&
1378 \& $x = \*(Aq(.)\e1\*(Aq; # Creates problems when concatenated.
1379 \& $y = \*(Aq(.)\eg{1}\*(Aq; # Avoids the problems.
1380 \& "aa" =~ /${x}/; # True
1381 \& "aa" =~ /${y}/; # True
1382 \& "aa0" =~ /${x}0/; # False!
1383 \& "aa0" =~ /${y}0/; # True
1384 \& "aa\ex08" =~ /${x}0/; # True!
1385 \& "aa\ex08" =~ /${y}0/; # False
1386 .Ve
1387 .PP
1388 Several special variables also refer back to portions of the previous
1389 match. \f(CW$+\fR returns whatever the last bracket match matched.
1390 \&\f(CW$&\fR returns the entire matched string. (At one point \f(CW$0\fR did
1391 also, but now it returns the name of the program.) \f(CW\*(C`$\`\*(C'\fR returns
1392 everything before the matched string. \f(CW\*(C`$\*(Aq\*(C'\fR returns everything
1393 after the matched string. And \f(CW$^N\fR contains whatever was matched by
1394 the most\-recently closed group (submatch). \f(CW$^N\fR can be used in
1395 extended patterns (see below), for example to assign a submatch to a
1396 variable.
1397 .IX Xref "$+ $^N $& $\\` $\\*(Aq"
1398 .PP
1399 These special variables, like the \f(CW\*(C`%+\*(C'\fR hash and the numbered match variables
1400 (\f(CW$1\fR, \f(CW$2\fR, \f(CW$3\fR, \fIetc\fR.) are dynamically scoped
1401 until the end of the enclosing block or until the next successful
1402 match, whichever comes first. (See "Compound Statements" in perlsyn.)
1403 .IX Xref "$+ $^N $& $\\` $\\*(Aq $1 $2 $3 $4 $5 $6 $7 $8 $9 @{^CAPTURE}"
1404 .PP
1405 The \f(CW\*(C`@{^CAPTURE}\*(C'\fR array may be used to access ALL of the capture buffers
1406 as an array without needing to know how many there are. For instance
1407 .PP
1408 .Vb 1
1409 \& $string=~/$pattern/ and @captured = @{^CAPTURE};
1410 .Ve
1411 .PP
1412 will place a copy of each capture variable, \f(CW$1\fR, \f(CW$2\fR etc, into the
1413 \&\f(CW@captured\fR array.
1414 .PP
1415 Be aware that when interpolating a subscript of the \f(CW\*(C`@{^CAPTURE}\*(C'\fR
1416 array you must use demarcated curly brace notation:
1417 .PP
1418 .Vb 1
1419 \& print "${^CAPTURE[0]}";
1420 .Ve
1421 .PP
1422 See "Demarcated variable names using braces" in perldata for more on
1423 this notation.
1424 .PP
1425 \&\fBNOTE\fR: Failed matches in Perl do not reset the match variables,
1426 which makes it easier to write code that tests for a series of more
1427 specific cases and remembers the best match.
1428 .PP
1429 \&\fBWARNING\fR: If your code is to run on Perl 5.16 or earlier,
1430 beware that once Perl sees that you need one of \f(CW$&\fR, \f(CW\*(C`$\`\*(C'\fR, or
1431 \&\f(CW\*(C`$\*(Aq\*(C'\fR anywhere in the program, it has to provide them for every
1432 pattern match. This may substantially slow your program.
1433 .PP
1434 Perl uses the same mechanism to produce \f(CW$1\fR, \f(CW$2\fR, \fIetc\fR, so you also
1435 pay a price for each pattern that contains capturing parentheses.
1436 (To avoid this cost while retaining the grouping behaviour, use the
1437 extended regular expression \f(CW\*(C`(?: ... )\*(C'\fR instead.) But if you never
1438 use \f(CW$&\fR, \f(CW\*(C`$\`\*(C'\fR or \f(CW\*(C`$\*(Aq\*(C'\fR, then patterns \fIwithout\fR capturing
1439 parentheses will not be penalized. So avoid \f(CW$&\fR, \f(CW\*(C`$\*(Aq\*(C'\fR, and \f(CW\*(C`$\`\*(C'\fR
1440 if you can, but if you can\*(Aqt (and some algorithms really appreciate
1441 them), once you\*(Aqve used them once, use them at will, because you\*(Aqve
1442 already paid the price.
1443 .IX Xref "$& $\\` $\\*(Aq"
1444 .PP
1445 Perl 5.16 introduced a slightly more efficient mechanism that notes
1446 separately whether each of \f(CW\*(C`$\`\*(C'\fR, \f(CW$&\fR, and \f(CW\*(C`$\*(Aq\*(C'\fR have been seen, and
1447 thus may only need to copy part of the string. Perl 5.20 introduced a
1448 much more efficient copy\-on\-write mechanism which eliminates any slowdown.
1449 .PP
1450 As another workaround for this problem, Perl 5.10.0 introduced \f(CW\*(C`${^PREMATCH}\*(C'\fR,
1451 \&\f(CW\*(C`${^MATCH}\*(C'\fR and \f(CW\*(C`${^POSTMATCH}\*(C'\fR, which are equivalent to \f(CW\*(C`$\`\*(C'\fR, \f(CW$&\fR
1452 and \f(CW\*(C`$\*(Aq\*(C'\fR, \fBexcept\fR that they are only guaranteed to be defined after a
1453 successful match that was executed with the \f(CW\*(C`/p\*(C'\fR (preserve) modifier.
1454 The use of these variables incurs no global performance penalty, unlike
1455 their punctuation character equivalents, however at the trade\-off that you
1456 have to tell perl when you want to use them.
1457 .IX Xref " p p modifier"
1458 .SS "Quoting (escaping) metacharacters"
1459 .IX Subsection "Quoting (escaping) metacharacters"
1460 To cause a metacharacter to match its literal self, you precede it with
1461 a backslash. Unlike some other regular expression languages, any
1462 sequence consisting of a backslash followed by a non\-alphanumeric
1463 matches that non\-alphanumeric, literally. So things like \f(CW\*(C`\e\e\*(C'\fR, \f(CW\*(C`\e(\*(C'\fR,
1464 \&\f(CW\*(C`\e)\*(C'\fR, \f(CW\*(C`\e[\*(C'\fR, \f(CW\*(C`\e]\*(C'\fR, \f(CW\*(C`\e{\*(C'\fR, or \f(CW\*(C`\e}\*(C'\fR are always interpreted as the
1465 literal character that follows the backslash.
1466 .PP
1467 (That\*(Aqs not true when an alphanumeric character is preceded by a
1468 backslash. There are a few such "escape sequences", like \f(CW\*(C`\ew\*(C'\fR, which have
1469 special matching behaviors in Perl. All such are currently limited to
1470 ASCII\-range alphanumerics.)
1471 .PP
1472 The best method to escape metacharacters is to use the
1473 \&\f(CWquotemeta()\fR function, or the equivalent, but the
1474 more flexible, and often more convenient, \f(CW\*(C`\eQ\*(C'\fR metaquoting escape
1475 sequence
1476 .PP
1477 .Vb 1
1478 \& quotemeta $pattern;
1479 .Ve
1480 .PP
1481 This changes \f(CW$pattern\fR so that the metacharacters are quoted. You can
1482 then do
1483 .PP
1484 .Vb 1
1485 \& $string =~ s/$pattern/foo/;
1486 .Ve
1487 .PP
1488 and be assured that any metacharacters in \f(CW$pattern\fR will match their
1489 literal selves. If you instead use \f(CW\*(C`\eQ\*(C'\fR, like:
1490 .PP
1491 .Vb 1
1492 \& $string =~ s/\eQpattern/foo/;
1493 .Ve
1494 .PP
1495 you don\*(Aqt have to have a separate \f(CW$pattern\fR variable. Further, there
1496 is an additional escape sequence, \f(CW\*(C`\eE\*(C'\fR that can be combined with \f(CW\*(C`\eQ\*(C'\fR
1497 to allow you to escape whatever portions of the pattern you desire:
1498 .PP
1499 .Vb 1
1500 \& $string =~ s/$unquoted\eQ$quoted\eE$unquoted/foo/;
1501 .Ve
1502 .PP
1503 Beware that if you put literal backslashes (those not inside
1504 interpolated variables) between \f(CW\*(C`\eQ\*(C'\fR and \f(CW\*(C`\eE\*(C'\fR, double\-quotish
1505 backslash interpolation may lead to confusing results. If you
1506 \&\fIneed\fR to use literal backslashes within \f(CW\*(C`\eQ...\eE\*(C'\fR,
1507 consult "Gory details of parsing quoted constructs" in perlop.
1508 .PP
1509 In older code, you may see something like this:
1510 .PP
1511 .Vb 2
1512 \& $pattern =~ s/(\eW)/\e\e$1/g;
1513 \& $string =~ s/$pattern/foo/;
1514 .Ve
1515 .PP
1516 This simply adds backslashes before all non\-"word" characters to disable
1517 any special meanings they might have. (If \f(CW\*(C`use\ locale\*(C'\fR is in
1518 effect, the current locale can affect the results.) This paradigm is
1519 inadequate for Unicode.
1520 .PP
1521 \&\f(CWquotemeta()\fR and \f(CW\*(C`\eQ\*(C'\fR are more fully described in
1522 "quotemeta" in perlfunc.
1523 .SS "Extended Patterns"
1524 .IX Subsection "Extended Patterns"
1525 Perl also defines a consistent extension syntax for features not
1526 found in standard tools like \fBawk\fR and
1527 \&\fBlex\fR. The syntax for most of these is a
1528 pair of parentheses with a question mark as the first thing within
1529 the parentheses. The character after the question mark indicates
1530 the extension.
1531 .PP
1532 A question mark was chosen for this and for the minimal\-matching
1533 construct because 1) question marks are rare in older regular
1534 expressions, and 2) whenever you see one, you should stop and
1535 "question" exactly what is going on. That\*(Aqs psychology....
1536 .ie n .IP """(?#\fItext\fR)""" 4
1537 .el .IP \f(CW(?#\fR\f(CItext\fR\f(CW)\fR 4
1538 .IX Xref "(?#)"
1539 .IX Item "(?#text)"
1540 A comment. The \fItext\fR is ignored.
1541 Note that Perl closes
1542 the comment as soon as it sees a \f(CW")"\fR, so there is no way to put a literal
1543 \&\f(CW")"\fR in the comment. The pattern\*(Aqs closing delimiter must be escaped by
1544 a backslash if it appears in the comment.
1545 .Sp
1546 See "/x" for another way to have comments in patterns.
1547 .Sp
1548 Note that a comment can go just about anywhere, except in the middle of
1549 an escape sequence. Examples:
1550 .Sp
1551 .Vb 1
1552 \& qr/foo(?#comment)bar/\*(Aq # Matches \*(Aqfoobar\*(Aq
1553 \&
1554 \& # The pattern below matches \*(Aqabcd\*(Aq, \*(Aqabccd\*(Aq, or \*(Aqabcccd\*(Aq
1555 \& qr/abc(?#comment between literal and its quantifier){1,3}d/
1556 \&
1557 \& # The pattern below generates a syntax error, because the \*(Aq\ep\*(Aq must
1558 \& # be followed immediately by a \*(Aq{\*(Aq.
1559 \& qr/\ep(?#comment between \ep and its property name){Any}/
1560 \&
1561 \& # The pattern below generates a syntax error, because the initial
1562 \& # \*(Aq\e(\*(Aq is a literal opening parenthesis, and so there is nothing
1563 \& # for the closing \*(Aq)\*(Aq to match
1564 \& qr/\e(?#the backslash means this isn\*(Aqt a comment)p{Any}/
1565 \&
1566 \& # Comments can be used to fold long patterns into multiple lines
1567 \& qr/First part of a long regex(?#
1568 \& )remaining part/
1569 .Ve
1570 .ie n .IP """(?adlupimnsx\-imnsx)""" 4
1571 .el .IP \f(CW(?adlupimnsx\-imnsx)\fR 4
1572 .IX Item "(?adlupimnsx-imnsx)"
1573 .PD 0
1574 .ie n .IP """(?^alupimnsx)""" 4
1575 .el .IP \f(CW(?^alupimnsx)\fR 4
1576 .IX Xref "(?) (?^)"
1577 .IX Item "(?^alupimnsx)"
1578 .PD
1579 Zero or more embedded pattern\-match modifiers, to be turned on (or
1580 turned off if preceded by \f(CW"\-"\fR) for the remainder of the pattern or
1581 the remainder of the enclosing pattern group (if any).
1582 .Sp
1583 This is particularly useful for dynamically\-generated patterns,
1584 such as those read in from a
1585 configuration file, taken from an argument, or specified in a table
1586 somewhere. Consider the case where some patterns want to be
1587 case\-sensitive and some do not: The case\-insensitive ones merely need to
1588 include \f(CW\*(C`(?i)\*(C'\fR at the front of the pattern. For example:
1589 .Sp
1590 .Vb 2
1591 \& $pattern = "foobar";
1592 \& if ( /$pattern/i ) { }
1593 \&
1594 \& # more flexible:
1595 \&
1596 \& $pattern = "(?i)foobar";
1597 \& if ( /$pattern/ ) { }
1598 .Ve
1599 .Sp
1600 These modifiers are restored at the end of the enclosing group. For example,
1601 .Sp
1602 .Vb 1
1603 \& ( (?i) blah ) \es+ \eg1
1604 .Ve
1605 .Sp
1606 will match \f(CW\*(C`blah\*(C'\fR in any case, some spaces, and an exact (\fIincluding the case\fR!)
1607 repetition of the previous word, assuming the \f(CW\*(C`/x\*(C'\fR modifier, and no \f(CW\*(C`/i\*(C'\fR
1608 modifier outside this group.
1609 .Sp
1610 These modifiers do not carry over into named subpatterns called in the
1611 enclosing group. In other words, a pattern such as \f(CW\*(C`((?i)(?&\fR\f(CINAME\fR\f(CW))\*(C'\fR does not
1612 change the case\-sensitivity of the \fINAME\fR pattern.
1613 .Sp
1614 A modifier is overridden by later occurrences of this construct in the
1615 same scope containing the same modifier, so that
1616 .Sp
1617 .Vb 1
1618 \& /((?im)foo(?\-m)bar)/
1619 .Ve
1620 .Sp
1621 matches all of \f(CW\*(C`foobar\*(C'\fR case insensitively, but uses \f(CW\*(C`/m\*(C'\fR rules for
1622 only the \f(CW\*(C`foo\*(C'\fR portion. The \f(CW"a"\fR flag overrides \f(CW\*(C`aa\*(C'\fR as well;
1623 likewise \f(CW\*(C`aa\*(C'\fR overrides \f(CW"a"\fR. The same goes for \f(CW"x"\fR and \f(CW\*(C`xx\*(C'\fR.
1624 Hence, in
1625 .Sp
1626 .Vb 1
1627 \& /(?\-x)foo/xx
1628 .Ve
1629 .Sp
1630 both \f(CW\*(C`/x\*(C'\fR and \f(CW\*(C`/xx\*(C'\fR are turned off during matching \f(CW\*(C`foo\*(C'\fR. And in
1631 .Sp
1632 .Vb 1
1633 \& /(?x)foo/x
1634 .Ve
1635 .Sp
1636 \&\f(CW\*(C`/x\*(C'\fR but NOT \f(CW\*(C`/xx\*(C'\fR is turned on for matching \f(CW\*(C`foo\*(C'\fR. (One might
1637 mistakenly think that since the inner \f(CW\*(C`(?x)\*(C'\fR is already in the scope of
1638 \&\f(CW\*(C`/x\*(C'\fR, that the result would effectively be the sum of them, yielding
1639 \&\f(CW\*(C`/xx\*(C'\fR. It doesn\*(Aqt work that way.) Similarly, doing something like
1640 \&\f(CW\*(C`(?xx\-x)foo\*(C'\fR turns off all \f(CW"x"\fR behavior for matching \f(CW\*(C`foo\*(C'\fR, it is not
1641 that you subtract 1 \f(CW"x"\fR from 2 to get 1 \f(CW"x"\fR remaining.
1642 .Sp
1643 Any of these modifiers can be set to apply globally to all regular
1644 expressions compiled within the scope of a \f(CW\*(C`use re\*(C'\fR. See
1645 "\*(Aq/flags\*(Aq mode" in re.
1646 .Sp
1647 Starting in Perl 5.14, a \f(CW"^"\fR (caret or circumflex accent) immediately
1648 after the \f(CW"?"\fR is a shorthand equivalent to \f(CW\*(C`d\-imnsx\*(C'\fR. Flags (except
1649 \&\f(CW"d"\fR) may follow the caret to override it.
1650 But a minus sign is not legal with it.
1651 .Sp
1652 Note that the \f(CW"a"\fR, \f(CW"d"\fR, \f(CW"l"\fR, \f(CW"p"\fR, and \f(CW"u"\fR modifiers are special in
1653 that they can only be enabled, not disabled, and the \f(CW"a"\fR, \f(CW"d"\fR, \f(CW"l"\fR, and
1654 \&\f(CW"u"\fR modifiers are mutually exclusive: specifying one de\-specifies the
1655 others, and a maximum of one (or two \f(CW"a"\fR\*(Aqs) may appear in the
1656 construct. Thus, for
1657 example, \f(CW\*(C`(?\-p)\*(C'\fR will warn when compiled under \f(CW\*(C`use warnings\*(C'\fR;
1658 \&\f(CW\*(C`(?\-d:...)\*(C'\fR and \f(CW\*(C`(?dl:...)\*(C'\fR are fatal errors.
1659 .Sp
1660 Note also that the \f(CW"p"\fR modifier is special in that its presence
1661 anywhere in a pattern has a global effect.
1662 .Sp
1663 Having zero modifiers makes this a no\-op (so why did you specify it,
1664 unless it\*(Aqs generated code), and starting in v5.30, warns under \f(CW\*(C`use
1665 re \*(Aqstrict\*(Aq\*(C'\fR.
1666 .ie n .IP """(?:\fIpattern\fR)""" 4
1667 .el .IP \f(CW(?:\fR\f(CIpattern\fR\f(CW)\fR 4
1668 .IX Xref "(?:)"
1669 .IX Item "(?:pattern)"
1670 .PD 0
1671 .ie n .IP """(?adluimnsx\-imnsx:\fIpattern\fR)""" 4
1672 .el .IP \f(CW(?adluimnsx\-imnsx:\fR\f(CIpattern\fR\f(CW)\fR 4
1673 .IX Item "(?adluimnsx-imnsx:pattern)"
1674 .ie n .IP """(?^aluimnsx:\fIpattern\fR)""" 4
1675 .el .IP \f(CW(?^aluimnsx:\fR\f(CIpattern\fR\f(CW)\fR 4
1676 .IX Xref "(?^:)"
1677 .IX Item "(?^aluimnsx:pattern)"
1678 .PD
1679 This is for clustering, not capturing; it groups subexpressions like
1680 \&\f(CW"()"\fR, but doesn\*(Aqt make backreferences as \f(CW"()"\fR does. So
1681 .Sp
1682 .Vb 1
1683 \& @fields = split(/\eb(?:a|b|c)\eb/)
1684 .Ve
1685 .Sp
1686 matches the same field delimiters as
1687 .Sp
1688 .Vb 1
1689 \& @fields = split(/\eb(a|b|c)\eb/)
1690 .Ve
1691 .Sp
1692 but doesn\*(Aqt spit out the delimiters themselves as extra fields (even though
1693 that\*(Aqs the behaviour of "split" in perlfunc when its pattern contains capturing
1694 groups). It\*(Aqs also cheaper not to capture
1695 characters if you don\*(Aqt need to.
1696 .Sp
1697 Any letters between \f(CW"?"\fR and \f(CW":"\fR act as flags modifiers as with
1698 \&\f(CW\*(C`(?adluimnsx\-imnsx)\*(C'\fR. For example,
1699 .Sp
1700 .Vb 1
1701 \& /(?s\-i:more.*than).*million/i
1702 .Ve
1703 .Sp
1704 is equivalent to the more verbose
1705 .Sp
1706 .Vb 1
1707 \& /(?:(?s\-i)more.*than).*million/i
1708 .Ve
1709 .Sp
1710 Note that any \f(CW\*(C`()\*(C'\fR constructs enclosed within this one will still
1711 capture unless the \f(CW\*(C`/n\*(C'\fR modifier is in effect.
1712 .Sp
1713 Like the "(?adlupimnsx\-imnsx)" construct, \f(CW\*(C`aa\*(C'\fR and \f(CW"a"\fR override each
1714 other, as do \f(CW\*(C`xx\*(C'\fR and \f(CW"x"\fR. They are not additive. So, doing
1715 something like \f(CW\*(C`(?xx\-x:foo)\*(C'\fR turns off all \f(CW"x"\fR behavior for matching
1716 \&\f(CW\*(C`foo\*(C'\fR.
1717 .Sp
1718 Starting in Perl 5.14, a \f(CW"^"\fR (caret or circumflex accent) immediately
1719 after the \f(CW"?"\fR is a shorthand equivalent to \f(CW\*(C`d\-imnsx\*(C'\fR. Any positive
1720 flags (except \f(CW"d"\fR) may follow the caret, so
1721 .Sp
1722 .Vb 1
1723 \& (?^x:foo)
1724 .Ve
1725 .Sp
1726 is equivalent to
1727 .Sp
1728 .Vb 1
1729 \& (?x\-imns:foo)
1730 .Ve
1731 .Sp
1732 The caret tells Perl that this cluster doesn\*(Aqt inherit the flags of any
1733 surrounding pattern, but uses the system defaults (\f(CW\*(C`d\-imnsx\*(C'\fR),
1734 modified by any flags specified.
1735 .Sp
1736 The caret allows for simpler stringification of compiled regular
1737 expressions. These look like
1738 .Sp
1739 .Vb 1
1740 \& (?^:pattern)
1741 .Ve
1742 .Sp
1743 with any non\-default flags appearing between the caret and the colon.
1744 A test that looks at such stringification thus doesn\*(Aqt need to have the
1745 system default flags hard\-coded in it, just the caret. If new flags are
1746 added to Perl, the meaning of the caret\*(Aqs expansion will change to include
1747 the default for those flags, so the test will still work, unchanged.
1748 .Sp
1749 Specifying a negative flag after the caret is an error, as the flag is
1750 redundant.
1751 .Sp
1752 Mnemonic for \f(CW\*(C`(?^...)\*(C'\fR: A fresh beginning since the usual use of a caret is
1753 to match at the beginning.
1754 .ie n .IP """(?|\fIpattern\fR)""" 4
1755 .el .IP \f(CW(?|\fR\f(CIpattern\fR\f(CW)\fR 4
1756 .IX Xref "(?|) Branch reset"
1757 .IX Item "(?|pattern)"
1758 This is the "branch reset" pattern, which has the special property
1759 that the capture groups are numbered from the same starting point
1760 in each alternation branch. It is available starting from perl 5.10.0.
1761 .Sp
1762 Capture groups are numbered from left to right, but inside this
1763 construct the numbering is restarted for each branch.
1764 .Sp
1765 The numbering within each branch will be as normal, and any groups
1766 following this construct will be numbered as though the construct
1767 contained only one branch, that being the one with the most capture
1768 groups in it.
1769 .Sp
1770 This construct is useful when you want to capture one of a
1771 number of alternative matches.
1772 .Sp
1773 Consider the following pattern. The numbers underneath show in
1774 which group the captured content will be stored.
1775 .Sp
1776 .Vb 3
1777 \& # before \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-branch\-reset\-\-\-\-\-\-\-\-\-\-\- after
1778 \& / ( a ) (?| x ( y ) z | (p (q) r) | (t) u (v) ) ( z ) /x
1779 \& # 1 2 2 3 2 3 4
1780 .Ve
1781 .Sp
1782 Be careful when using the branch reset pattern in combination with
1783 named captures. Named captures are implemented as being aliases to
1784 numbered groups holding the captures, and that interferes with the
1785 implementation of the branch reset pattern. If you are using named
1786 captures in a branch reset pattern, it\*(Aqs best to use the same names,
1787 in the same order, in each of the alternations:
1788 .Sp
1789 .Vb 2
1790 \& /(?| (?<a> x ) (?<b> y )
1791 \& | (?<a> z ) (?<b> w )) /x
1792 .Ve
1793 .Sp
1794 Not doing so may lead to surprises:
1795 .Sp
1796 .Vb 3
1797 \& "12" =~ /(?| (?<a> \ed+ ) | (?<b> \eD+))/x;
1798 \& say $+{a}; # Prints \*(Aq12\*(Aq
1799 \& say $+{b}; # *Also* prints \*(Aq12\*(Aq.
1800 .Ve
1801 .Sp
1802 The problem here is that both the group named \f(CW\*(C`a\*(C'\fR and the group
1803 named \f(CW\*(C`b\*(C'\fR are aliases for the group belonging to \f(CW$1\fR.
1804 .IP "Lookaround Assertions" 4
1805 .IX Xref "look-around assertion lookaround assertion look-around lookaround"
1806 .IX Item "Lookaround Assertions"
1807 Lookaround assertions are zero\-width patterns which match a specific
1808 pattern without including it in \f(CW$&\fR. Positive assertions match when
1809 their subpattern matches, negative assertions match when their subpattern
1810 fails. Lookbehind matches text up to the current match position,
1811 lookahead matches text following the current match position.
1812 .RS 4
1813 .ie n .IP """(?=\fIpattern\fR)""" 4
1814 .el .IP \f(CW(?=\fR\f(CIpattern\fR\f(CW)\fR 4
1815 .IX Item "(?=pattern)"
1816 .PD 0
1817 .ie n .IP """(*pla:\fIpattern\fR)""" 4
1818 .el .IP \f(CW(*pla:\fR\f(CIpattern\fR\f(CW)\fR 4
1819 .IX Item "(*pla:pattern)"
1820 .ie n .IP """(*positive_lookahead:\fIpattern\fR)""" 4
1821 .el .IP \f(CW(*positive_lookahead:\fR\f(CIpattern\fR\f(CW)\fR 4
1822 .IX Xref "(?=) (*pla (*positive_lookahead look-ahead, positive lookahead, positive"
1823 .IX Item "(*positive_lookahead:pattern)"
1824 .PD
1825 A zero\-width positive lookahead assertion. For example, \f(CW\*(C`/\ew+(?=\et)/\*(C'\fR
1826 matches a word followed by a tab, without including the tab in \f(CW$&\fR.
1827 .ie n .IP """(?!\fIpattern\fR)""" 4
1828 .el .IP \f(CW(?!\fR\f(CIpattern\fR\f(CW)\fR 4
1829 .IX Item "(?!pattern)"
1830 .PD 0
1831 .ie n .IP """(*nla:\fIpattern\fR)""" 4
1832 .el .IP \f(CW(*nla:\fR\f(CIpattern\fR\f(CW)\fR 4
1833 .IX Item "(*nla:pattern)"
1834 .ie n .IP """(*negative_lookahead:\fIpattern\fR)""" 4
1835 .el .IP \f(CW(*negative_lookahead:\fR\f(CIpattern\fR\f(CW)\fR 4
1836 .IX Xref "(?!) (*nla (*negative_lookahead look-ahead, negative lookahead, negative"
1837 .IX Item "(*negative_lookahead:pattern)"
1838 .PD
1839 A zero\-width negative lookahead assertion. For example \f(CW\*(C`/foo(?!bar)/\*(C'\fR
1840 matches any occurrence of "foo" that isn\*(Aqt followed by "bar". Note
1841 however that lookahead and lookbehind are NOT the same thing. You cannot
1842 use this for lookbehind.
1843 .Sp
1844 If you are looking for a "bar" that isn\*(Aqt preceded by a "foo", \f(CW\*(C`/(?!foo)bar/\*(C'\fR
1845 will not do what you want. That\*(Aqs because the \f(CW\*(C`(?!foo)\*(C'\fR is just saying that
1846 the next thing cannot be "foo"\-\-and it\*(Aqs not, it\*(Aqs a "bar", so "foobar" will
1847 match. Use lookbehind instead (see below).
1848 .ie n .IP """(?<=\fIpattern\fR)""" 4
1849 .el .IP \f(CW(?<=\fR\f(CIpattern\fR\f(CW)\fR 4
1850 .IX Item "(?<=pattern)"
1851 .PD 0
1852 .ie n .IP """\eK""" 4
1853 .el .IP \f(CW\eK\fR 4
1854 .IX Item "K"
1855 .ie n .IP """(*plb:\fIpattern\fR)""" 4
1856 .el .IP \f(CW(*plb:\fR\f(CIpattern\fR\f(CW)\fR 4
1857 .IX Item "(*plb:pattern)"
1858 .ie n .IP """(*positive_lookbehind:\fIpattern\fR)""" 4
1859 .el .IP \f(CW(*positive_lookbehind:\fR\f(CIpattern\fR\f(CW)\fR 4
1860 .IX Xref "(?<=) (*plb (*positive_lookbehind look-behind, positive lookbehind, positive \\K"
1861 .IX Item "(*positive_lookbehind:pattern)"
1862 .PD
1863 A zero\-width positive lookbehind assertion. For example, \f(CW\*(C`/(?<=\et)\ew+/\*(C'\fR
1864 matches a word that follows a tab, without including the tab in \f(CW$&\fR.
1865 .Sp
1866 Prior to Perl 5.30, it worked only for fixed\-width lookbehind, but
1867 starting in that release, it can handle variable lengths from 1 to 255
1868 characters as an experimental feature. The feature is enabled
1869 automatically if you use a variable length positive lookbehind assertion.
1870 .Sp
1871 In Perl 5.35.10 the scope of the experimental nature of this construct
1872 has been reduced, and experimental warnings will only be produced when
1873 the construct contains capturing parentheses. The warnings will be
1874 raised at pattern compilation time, unless turned off, in the
1875 \&\f(CW\*(C`experimental::vlb\*(C'\fR category. This is to warn you that the exact
1876 contents of capturing buffers in a variable length positive lookbehind
1877 is not well defined and is subject to change in a future release of perl.
1878 .Sp
1879 Currently if you use capture buffers inside of a positive variable length
1880 lookbehind the result will be the longest and thus leftmost match possible.
1881 This means that
1882 .Sp
1883 .Vb 4
1884 \& "aax" =~ /(?=x)(?<=(a|aa))/
1885 \& "aax" =~ /(?=x)(?<=(aa|a))/
1886 \& "aax" =~ /(?=x)(?<=(a{1,2}?)/
1887 \& "aax" =~ /(?=x)(?<=(a{1,2})/
1888 .Ve
1889 .Sp
1890 will all result in \f(CW$1\fR containing \f(CW"aa"\fR. It is possible in a future
1891 release of perl we will change this behavior.
1892 .Sp
1893 There is a special form of this construct, called \f(CW\*(C`\eK\*(C'\fR
1894 (available since Perl 5.10.0), which causes the
1895 regex engine to "keep" everything it had matched prior to the \f(CW\*(C`\eK\*(C'\fR and
1896 not include it in \f(CW$&\fR. This effectively provides non\-experimental
1897 variable\-length lookbehind of any length.
1898 .Sp
1899 And, there is a technique that can be used to handle variable length
1900 lookbehinds on earlier releases, and longer than 255 characters. It is
1901 described in
1902 <http://www.drregex.com/2019/02/variable\-length\-lookbehinds\-actually.html>.
1903 .Sp
1904 Note that under \f(CW\*(C`/i\*(C'\fR, a few single characters match two or three other
1905 characters. This makes them variable length, and the 255 length applies
1906 to the maximum number of characters in the match. For
1907 example \f(CW\*(C`qr/\eN{LATIN SMALL LETTER SHARP S}/i\*(C'\fR matches the sequence
1908 \&\f(CW"ss"\fR. Your lookbehind assertion could contain 127 Sharp S
1909 characters under \f(CW\*(C`/i\*(C'\fR, but adding a 128th would generate a compilation
1910 error, as that could match 256 \f(CW"s"\fR characters in a row.
1911 .Sp
1912 The use of \f(CW\*(C`\eK\*(C'\fR inside of another lookaround assertion
1913 is allowed, but the behaviour is currently not well defined.
1914 .Sp
1915 For various reasons \f(CW\*(C`\eK\*(C'\fR may be significantly more efficient than the
1916 equivalent \f(CW\*(C`(?<=...)\*(C'\fR construct, and it is especially useful in
1917 situations where you want to efficiently remove something following
1918 something else in a string. For instance
1919 .Sp
1920 .Vb 1
1921 \& s/(foo)bar/$1/g;
1922 .Ve
1923 .Sp
1924 can be rewritten as the much more efficient
1925 .Sp
1926 .Vb 1
1927 \& s/foo\eKbar//g;
1928 .Ve
1929 .Sp
1930 Use of the non\-greedy modifier \f(CW"?"\fR may not give you the expected
1931 results if it is within a capturing group within the construct.
1932 .ie n .IP """(?<!\fIpattern\fR)""" 4
1933 .el .IP \f(CW(?<!\fR\f(CIpattern\fR\f(CW)\fR 4
1934 .IX Item "(?<!pattern)"
1935 .PD 0
1936 .ie n .IP """(*nlb:\fIpattern\fR)""" 4
1937 .el .IP \f(CW(*nlb:\fR\f(CIpattern\fR\f(CW)\fR 4
1938 .IX Item "(*nlb:pattern)"
1939 .ie n .IP """(*negative_lookbehind:\fIpattern\fR)""" 4
1940 .el .IP \f(CW(*negative_lookbehind:\fR\f(CIpattern\fR\f(CW)\fR 4
1941 .IX Xref "(?<!) (*nlb (*negative_lookbehind look-behind, negative lookbehind, negative"
1942 .IX Item "(*negative_lookbehind:pattern)"
1943 .PD
1944 A zero\-width negative lookbehind assertion. For example \f(CW\*(C`/(?<!bar)foo/\*(C'\fR
1945 matches any occurrence of "foo" that does not follow "bar".
1946 .Sp
1947 Prior to Perl 5.30, it worked only for fixed\-width lookbehind, but
1948 starting in that release, it can handle variable lengths from 1 to 255
1949 characters as an experimental feature. The feature is enabled
1950 automatically if you use a variable length negative lookbehind assertion.
1951 .Sp
1952 In Perl 5.35.10 the scope of the experimental nature of this construct
1953 has been reduced, and experimental warnings will only be produced when
1954 the construct contains capturing parentheses. The warnings will be
1955 raised at pattern compilation time, unless turned off, in the
1956 \&\f(CW\*(C`experimental::vlb\*(C'\fR category. This is to warn you that the exact
1957 contents of capturing buffers in a variable length negative lookbehind
1958 is not well defined and is subject to change in a future release of perl.
1959 .Sp
1960 Currently if you use capture buffers inside of a negative variable length
1961 lookbehind the result may not be what you expect, for instance:
1962 .Sp
1963 .Vb 1
1964 \& say "axfoo"=~/(?=foo)(?<!(a|ax)(?{ say $1 }))/ ? "y" : "n";
1965 .Ve
1966 .Sp
1967 will output the following:
1968 .Sp
1969 .Vb 2
1970 \& a
1971 \& no
1972 .Ve
1973 .Sp
1974 which does not make sense as this should print out "ax" as the "a" does
1975 not line up at the correct place. Another example would be:
1976 .Sp
1977 .Vb 1
1978 \& say "yes: \*(Aq$1\-$2\*(Aq" if "aayfoo"=~/(?=foo)(?<!(a|aa)(a|aa)x)/;
1979 .Ve
1980 .Sp
1981 will output the following:
1982 .Sp
1983 .Vb 1
1984 \& yes: \*(Aqaa\-a\*(Aq
1985 .Ve
1986 .Sp
1987 It is possible in a future release of perl we will change this behavior
1988 so both of these examples produced more reasonable output.
1989 .Sp
1990 Note that we are confident that the construct will match and reject
1991 patterns appropriately, the undefined behavior strictly relates to the
1992 value of the capture buffer during or after matching.
1993 .Sp
1994 There is a technique that can be used to handle variable length
1995 lookbehind on earlier releases, and longer than 255 characters. It is
1996 described in
1997 <http://www.drregex.com/2019/02/variable\-length\-lookbehinds\-actually.html>.
1998 .Sp
1999 Note that under \f(CW\*(C`/i\*(C'\fR, a few single characters match two or three other
2000 characters. This makes them variable length, and the 255 length applies
2001 to the maximum number of characters in the match. For
2002 example \f(CW\*(C`qr/\eN{LATIN SMALL LETTER SHARP S}/i\*(C'\fR matches the sequence
2003 \&\f(CW"ss"\fR. Your lookbehind assertion could contain 127 Sharp S
2004 characters under \f(CW\*(C`/i\*(C'\fR, but adding a 128th would generate a compilation
2005 error, as that could match 256 \f(CW"s"\fR characters in a row.
2006 .Sp
2007 Use of the non\-greedy modifier \f(CW"?"\fR may not give you the expected
2008 results if it is within a capturing group within the construct.
2009 .RE
2010 .RS 4
2011 .RE
2012 .ie n .IP """(?<\fINAME\fR>\fIpattern\fR)""" 4
2013 .el .IP \f(CW(?<\fR\f(CINAME\fR\f(CW>\fR\f(CIpattern\fR\f(CW)\fR 4
2014 .IX Item "(?<NAME>pattern)"
2015 .PD 0
2016 .ie n .IP """(?\*(Aq\fINAME\fR\*(Aq\fIpattern\fR)""" 4
2017 .el .IP \f(CW(?\*(Aq\fR\f(CINAME\fR\f(CW\*(Aq\fR\f(CIpattern\fR\f(CW)\fR 4
2018 .IX Xref "(?<NAME>) (?\\*(AqNAME\\*(Aq) named capture capture"
2019 .IX Item "(?'NAME'pattern)"
2020 .PD
2021 A named capture group. Identical in every respect to normal capturing
2022 parentheses \f(CW\*(C`()\*(C'\fR but for the additional fact that the group
2023 can be referred to by name in various regular expression
2024 constructs (like \f(CW\*(C`\eg{\fR\f(CINAME\fR\f(CW}\*(C'\fR) and can be accessed by name
2025 after a successful match via \f(CW\*(C`%+\*(C'\fR or \f(CW\*(C`%\-\*(C'\fR. See perlvar
2026 for more details on the \f(CW\*(C`%+\*(C'\fR and \f(CW\*(C`%\-\*(C'\fR hashes.
2027 .Sp
2028 If multiple distinct capture groups have the same name, then
2029 \&\f(CW$+{\fR\f(CINAME\fR\f(CW}\fR will refer to the leftmost defined group in the match.
2030 .Sp
2031 The forms \f(CW\*(C`(?\*(Aq\fR\f(CINAME\fR\f(CW\*(Aq\fR\f(CIpattern\fR\f(CW)\*(C'\fR and \f(CW\*(C`(?<\fR\f(CINAME\fR\f(CW>\fR\f(CIpattern\fR\f(CW)\*(C'\fR
2032 are equivalent.
2033 .Sp
2034 \&\fBNOTE:\fR While the notation of this construct is the same as the similar
2035 function in .NET regexes, the behavior is not. In Perl the groups are
2036 numbered sequentially regardless of being named or not. Thus in the
2037 pattern
2038 .Sp
2039 .Vb 1
2040 \& /(x)(?<foo>y)(z)/
2041 .Ve
2042 .Sp
2043 \&\f(CW$+{foo}\fR will be the same as \f(CW$2\fR, and \f(CW$3\fR will contain \*(Aqz\*(Aq instead of
2044 the opposite which is what a .NET regex hacker might expect.
2045 .Sp
2046 Currently \fINAME\fR is restricted to simple identifiers only.
2047 In other words, it must match \f(CW\*(C`/^[_A\-Za\-z][_A\-Za\-z0\-9]*\ez/\*(C'\fR or
2048 its Unicode extension (see utf8),
2049 though it isn\*(Aqt extended by the locale (see perllocale).
2050 .Sp
2051 \&\fBNOTE:\fR In order to make things easier for programmers with experience
2052 with the Python or PCRE regex engines, the pattern \f(CW\*(C`(?P<\fR\f(CINAME\fR\f(CW>\fR\f(CIpattern\fR\f(CW)\*(C'\fR
2053 may be used instead of \f(CW\*(C`(?<\fR\f(CINAME\fR\f(CW>\fR\f(CIpattern\fR\f(CW)\*(C'\fR; however this form does not
2054 support the use of single quotes as a delimiter for the name.
2055 .ie n .IP """\ek<\fINAME\fR>""" 4
2056 .el .IP \f(CW\ek<\fR\f(CINAME\fR\f(CW>\fR 4
2057 .IX Item "k<NAME>"
2058 .PD 0
2059 .ie n .IP """\ek\*(Aq\fINAME\fR\*(Aq""" 4
2060 .el .IP \f(CW\ek\*(Aq\fR\f(CINAME\fR\f(CW\*(Aq\fR 4
2061 .IX Item "k'NAME'"
2062 .ie n .IP """\ek{\fINAME\fR}""" 4
2063 .el .IP \f(CW\ek{\fR\f(CINAME\fR\f(CW}\fR 4
2064 .IX Item "k{NAME}"
2065 .PD
2066 Named backreference. Similar to numeric backreferences, except that
2067 the group is designated by name and not number. If multiple groups
2068 have the same name then it refers to the leftmost defined group in
2069 the current match.
2070 .Sp
2071 It is an error to refer to a name not defined by a \f(CW\*(C`(?<\fR\f(CINAME\fR\f(CW>)\*(C'\fR
2072 earlier in the pattern.
2073 .Sp
2074 All three forms are equivalent, although with \f(CW\*(C`\ek{ \fR\f(CINAME\fR\f(CW }\*(C'\fR,
2075 you may optionally have blanks within but adjacent to the braces, as
2076 shown.
2077 .Sp
2078 \&\fBNOTE:\fR In order to make things easier for programmers with experience
2079 with the Python or PCRE regex engines, the pattern \f(CW\*(C`(?P=\fR\f(CINAME\fR\f(CW)\*(C'\fR
2080 may be used instead of \f(CW\*(C`\ek<\fR\f(CINAME\fR\f(CW>\*(C'\fR.
2081 .ie n .IP """(?{ \fIcode\fR })""" 4
2082 .el .IP "\f(CW(?{ \fR\f(CIcode\fR\f(CW })\fR" 4
2083 .IX Xref "(?{}) regex, code in regexp, code in regular expression, code in"
2084 .IX Item "(?{ code })"
2085 \&\fBWARNING\fR: Using this feature safely requires that you understand its
2086 limitations. Code executed that has side effects may not perform identically
2087 from version to version due to the effect of future optimisations in the regex
2088 engine. For more information on this, see "Embedded Code Execution
2089 Frequency".
2090 .Sp
2091 This zero\-width assertion executes any embedded Perl code. It always
2092 succeeds, and its return value is set as \f(CW$^R\fR.
2093 .Sp
2094 In literal patterns, the code is parsed at the same time as the
2095 surrounding code. While within the pattern, control is passed temporarily
2096 back to the perl parser, until the logically\-balancing closing brace is
2097 encountered. This is similar to the way that an array index expression in
2098 a literal string is handled, for example
2099 .Sp
2100 .Vb 1
2101 \& "abc$array[ 1 + f(\*(Aq[\*(Aq) + g()]def"
2102 .Ve
2103 .Sp
2104 In particular, braces do not need to be balanced:
2105 .Sp
2106 .Vb 1
2107 \& s/abc(?{ f(\*(Aq{\*(Aq); })/def/
2108 .Ve
2109 .Sp
2110 Even in a pattern that is interpolated and compiled at run\-time, literal
2111 code blocks will be compiled once, at perl compile time; the following
2112 prints "ABCD":
2113 .Sp
2114 .Vb 5
2115 \& print "D";
2116 \& my $qr = qr/(?{ BEGIN { print "A" } })/;
2117 \& my $foo = "foo";
2118 \& /$foo$qr(?{ BEGIN { print "B" } })/;
2119 \& BEGIN { print "C" }
2120 .Ve
2121 .Sp
2122 In patterns where the text of the code is derived from run\-time
2123 information rather than appearing literally in a source code /pattern/,
2124 the code is compiled at the same time that the pattern is compiled, and
2125 for reasons of security, \f(CW\*(C`use re \*(Aqeval\*(Aq\*(C'\fR must be in scope. This is to
2126 stop user\-supplied patterns containing code snippets from being
2127 executable.
2128 .Sp
2129 In situations where you need to enable this with \f(CW\*(C`use re \*(Aqeval\*(Aq\*(C'\fR, you should
2130 also have taint checking enabled, if your perl supports it.
2131 Better yet, use the carefully constrained evaluation within a Safe compartment.
2132 See perlsec for details about both these mechanisms.
2133 .Sp
2134 From the viewpoint of parsing, lexical variable scope and closures,
2135 .Sp
2136 .Vb 1
2137 \& /AAA(?{ BBB })CCC/
2138 .Ve
2139 .Sp
2140 behaves approximately like
2141 .Sp
2142 .Vb 1
2143 \& /AAA/ && do { BBB } && /CCC/
2144 .Ve
2145 .Sp
2146 Similarly,
2147 .Sp
2148 .Vb 1
2149 \& qr/AAA(?{ BBB })CCC/
2150 .Ve
2151 .Sp
2152 behaves approximately like
2153 .Sp
2154 .Vb 1
2155 \& sub { /AAA/ && do { BBB } && /CCC/ }
2156 .Ve
2157 .Sp
2158 In particular:
2159 .Sp
2160 .Vb 3
2161 \& { my $i = 1; $r = qr/(?{ print $i })/ }
2162 \& my $i = 2;
2163 \& /$r/; # prints "1"
2164 .Ve
2165 .Sp
2166 Inside a \f(CW\*(C`(?{...})\*(C'\fR block, \f(CW$_\fR refers to the string the regular
2167 expression is matching against. You can also use \f(CWpos()\fR to know what is
2168 the current position of matching within this string.
2169 .Sp
2170 The code block introduces a new scope from the perspective of lexical
2171 variable declarations, but \fBnot\fR from the perspective of \f(CW\*(C`local\*(C'\fR and
2172 similar localizing behaviours. So later code blocks within the same
2173 pattern will still see the values which were localized in earlier blocks.
2174 These accumulated localizations are undone either at the end of a
2175 successful match, or if the assertion is backtracked (compare
2176 "Backtracking"). For example,
2177 .Sp
2178 .Vb 10
2179 \& $_ = \*(Aqa\*(Aq x 8;
2180 \& m<
2181 \& (?{ $cnt = 0 }) # Initialize $cnt.
2182 \& (
2183 \& a
2184 \& (?{
2185 \& local $cnt = $cnt + 1; # Update $cnt,
2186 \& # backtracking\-safe.
2187 \& })
2188 \& )*
2189 \& aaaa
2190 \& (?{ $res = $cnt }) # On success copy to
2191 \& # non\-localized location.
2192 \& >x;
2193 .Ve
2194 .Sp
2195 will initially increment \f(CW$cnt\fR up to 8; then during backtracking, its
2196 value will be unwound back to 4, which is the value assigned to \f(CW$res\fR.
2197 At the end of the regex execution, \f(CW$cnt\fR will be wound back to its initial
2198 value of 0.
2199 .Sp
2200 This assertion may be used as the condition in a
2201 .Sp
2202 .Vb 1
2203 \& (?(condition)yes\-pattern|no\-pattern)
2204 .Ve
2205 .Sp
2206 switch. If \fInot\fR used in this way, the result of evaluation of \fIcode\fR
2207 is put into the special variable \f(CW$^R\fR. This happens immediately, so
2208 \&\f(CW$^R\fR can be used from other \f(CW\*(C`(?{ \fR\f(CIcode\fR\f(CW })\*(C'\fR assertions inside the same
2209 regular expression.
2210 .Sp
2211 The assignment to \f(CW$^R\fR above is properly localized, so the old
2212 value of \f(CW$^R\fR is restored if the assertion is backtracked; compare
2213 "Backtracking".
2214 .Sp
2215 Note that the special variable \f(CW$^N\fR is particularly useful with code
2216 blocks to capture the results of submatches in variables without having to
2217 keep track of the number of nested parentheses. For example:
2218 .Sp
2219 .Vb 3
2220 \& $_ = "The brown fox jumps over the lazy dog";
2221 \& /the (\eS+)(?{ $color = $^N }) (\eS+)(?{ $animal = $^N })/i;
2222 \& print "color = $color, animal = $animal\en";
2223 .Ve
2224 .Sp
2225 The use of this construct disables some optimisations globally in the
2226 pattern, and the pattern may execute much slower as a consequence.
2227 Use a \f(CW\*(C`*\*(C'\fR instead of the \f(CW\*(C`?\*(C'\fR block to create an optimistic form of
2228 this construct. \f(CW\*(C`(*{ ... })\*(C'\fR should not disable any optimisations.
2229 .ie n .IP """(*{ \fIcode\fR })""" 4
2230 .el .IP "\f(CW(*{ \fR\f(CIcode\fR\f(CW })\fR" 4
2231 .IX Xref "(*{}) regex, optimistic code"
2232 .IX Item "(*{ code })"
2233 This is *exactly* the same as \f(CW\*(C`(?{ \fR\f(CIcode\fR\f(CW })\*(C'\fR with the exception
2234 that it does not disable \fBany\fR optimisations at all in the regex engine.
2235 How often it is executed may vary from perl release to perl release.
2236 In a failing match it may not even be executed at all.
2237 .ie n .IP """(??{ \fIcode\fR })""" 4
2238 .el .IP "\f(CW(??{ \fR\f(CIcode\fR\f(CW })\fR" 4
2239 .IX Xref "(??{}) regex, postponed regexp, postponed regular expression, postponed"
2240 .IX Item "(??{ code })"
2241 \&\fBWARNING\fR: Using this feature safely requires that you understand its
2242 limitations. Code executed that has side effects may not perform
2243 identically from version to version due to the effect of future
2244 optimisations in the regex engine. For more information on this, see
2245 "Embedded Code Execution Frequency".
2246 .Sp
2247 This is a "postponed" regular subexpression. It behaves in \fIexactly\fR the
2248 same way as a \f(CW\*(C`(?{ \fR\f(CIcode\fR\f(CW })\*(C'\fR code block as described above, except that
2249 its return value, rather than being assigned to \f(CW$^R\fR, is treated as a
2250 pattern, compiled if it\*(Aqs a string (or used as\-is if it\*(Aqs a qr// object),
2251 then matched as if it were inserted instead of this construct.
2252 .Sp
2253 During the matching of this sub\-pattern, it has its own set of
2254 captures which are valid during the sub\-match, but are discarded once
2255 control returns to the main pattern. For example, the following matches,
2256 with the inner pattern capturing "B" and matching "BB", while the outer
2257 pattern captures "A";
2258 .Sp
2259 .Vb 3
2260 \& my $inner = \*(Aq(.)\e1\*(Aq;
2261 \& "ABBA" =~ /^(.)(??{ $inner })\e1/;
2262 \& print $1; # prints "A";
2263 .Ve
2264 .Sp
2265 Note that this means that there is no way for the inner pattern to refer
2266 to a capture group defined outside. (The code block itself can use \f(CW$1\fR,
2267 \&\fIetc\fR., to refer to the enclosing pattern\*(Aqs capture groups.) Thus, although
2268 .Sp
2269 .Vb 1
2270 \& (\*(Aqa\*(Aq x 100)=~/(??{\*(Aq(.)\*(Aq x 100})/
2271 .Ve
2272 .Sp
2273 \&\fIwill\fR match, it will \fInot\fR set \f(CW$1\fR on exit.
2274 .Sp
2275 The following pattern matches a parenthesized group:
2276 .Sp
2277 .Vb 9
2278 \& $re = qr{
2279 \& \e(
2280 \& (?:
2281 \& (?> [^()]+ ) # Non\-parens without backtracking
2282 \& |
2283 \& (??{ $re }) # Group with matching parens
2284 \& )*
2285 \& \e)
2286 \& }x;
2287 .Ve
2288 .Sp
2289 See also
2290 \&\f(CW\*(C`(?\fR\f(CIPARNO\fR\f(CW)\*(C'\fR
2291 for a different, more efficient way to accomplish
2292 the same task.
2293 .Sp
2294 Executing a postponed regular expression too many times without
2295 consuming any input string will also result in a fatal error. The depth
2296 at which that happens is compiled into perl, so it can be changed with a
2297 custom build.
2298 .Sp
2299 The use of this construct disables some optimisations globally in the pattern,
2300 and the pattern may execute much slower as a consequence.
2301 .ie n .IP """(?\fIPARNO\fR)"" ""(?\-\fIPARNO\fR)"" ""(?+\fIPARNO\fR)"" ""(?R)"" ""(?0)""" 4
2302 .el .IP "\f(CW(?\fR\f(CIPARNO\fR\f(CW)\fR \f(CW(?\-\fR\f(CIPARNO\fR\f(CW)\fR \f(CW(?+\fR\f(CIPARNO\fR\f(CW)\fR \f(CW(?R)\fR \f(CW(?0)\fR" 4
2303 .IX Xref "(?PARNO) (?1) (?R) (?0) (?-1) (?+1) (?-PARNO) (?+PARNO) regex, recursive regexp, recursive regular expression, recursive regex, relative recursion GOSUB GOSTART"
2304 .IX Item "(?PARNO) (?-PARNO) (?+PARNO) (?R) (?0)"
2305 Recursive subpattern. Treat the contents of a given capture buffer in the
2306 current pattern as an independent subpattern and attempt to match it at
2307 the current position in the string. Information about capture state from
2308 the caller for things like backreferences is available to the subpattern,
2309 but capture buffers set by the subpattern are not visible to the caller.
2310 .Sp
2311 Similar to \f(CW\*(C`(??{ \fR\f(CIcode\fR\f(CW })\*(C'\fR except that it does not involve executing any
2312 code or potentially compiling a returned pattern string; instead it treats
2313 the part of the current pattern contained within a specified capture group
2314 as an independent pattern that must match at the current position. Also
2315 different is the treatment of capture buffers, unlike \f(CW\*(C`(??{ \fR\f(CIcode\fR\f(CW })\*(C'\fR
2316 recursive patterns have access to their caller\*(Aqs match state, so one can
2317 use backreferences safely.
2318 .Sp
2319 \&\fIPARNO\fR is a sequence of digits (not starting with 0) whose value reflects
2320 the paren\-number of the capture group to recurse to. \f(CW\*(C`(?R)\*(C'\fR recurses to
2321 the beginning of the whole pattern. \f(CW\*(C`(?0)\*(C'\fR is an alternate syntax for
2322 \&\f(CW\*(C`(?R)\*(C'\fR. If \fIPARNO\fR is preceded by a plus or minus sign then it is assumed
2323 to be relative, with negative numbers indicating preceding capture groups
2324 and positive ones following. Thus \f(CW\*(C`(?\-1)\*(C'\fR refers to the most recently
2325 declared group, and \f(CW\*(C`(?+1)\*(C'\fR indicates the next group to be declared.
2326 Note that the counting for relative recursion differs from that of
2327 relative backreferences, in that with recursion unclosed groups \fBare\fR
2328 included.
2329 .Sp
2330 The following pattern matches a function \f(CWfoo()\fR which may contain
2331 balanced parentheses as the argument.
2332 .Sp
2333 .Vb 10
2334 \& $re = qr{ ( # paren group 1 (full function)
2335 \& foo
2336 \& ( # paren group 2 (parens)
2337 \& \e(
2338 \& ( # paren group 3 (contents of parens)
2339 \& (?:
2340 \& (?> [^()]+ ) # Non\-parens without backtracking
2341 \& |
2342 \& (?2) # Recurse to start of paren group 2
2343 \& )*
2344 \& )
2345 \& \e)
2346 \& )
2347 \& )
2348 \& }x;
2349 .Ve
2350 .Sp
2351 If the pattern was used as follows
2352 .Sp
2353 .Vb 4
2354 \& \*(Aqfoo(bar(baz)+baz(bop))\*(Aq=~/$re/
2355 \& and print "\e$1 = $1\en",
2356 \& "\e$2 = $2\en",
2357 \& "\e$3 = $3\en";
2358 .Ve
2359 .Sp
2360 the output produced should be the following:
2361 .Sp
2362 .Vb 3
2363 \& $1 = foo(bar(baz)+baz(bop))
2364 \& $2 = (bar(baz)+baz(bop))
2365 \& $3 = bar(baz)+baz(bop)
2366 .Ve
2367 .Sp
2368 If there is no corresponding capture group defined, then it is a
2369 fatal error. Recursing deeply without consuming any input string will
2370 also result in a fatal error. The depth at which that happens is
2371 compiled into perl, so it can be changed with a custom build.
2372 .Sp
2373 The following shows how using negative indexing can make it
2374 easier to embed recursive patterns inside of a \f(CW\*(C`qr//\*(C'\fR construct
2375 for later use:
2376 .Sp
2377 .Vb 4
2378 \& my $parens = qr/(\e((?:[^()]++|(?\-1))*+\e))/;
2379 \& if (/foo $parens \es+ \e+ \es+ bar $parens/x) {
2380 \& # do something here...
2381 \& }
2382 .Ve
2383 .Sp
2384 \&\fBNote\fR that this pattern does not behave the same way as the equivalent
2385 PCRE or Python construct of the same form. In Perl you can backtrack into
2386 a recursed group, in PCRE and Python the recursed into group is treated
2387 as atomic. Also, modifiers are resolved at compile time, so constructs
2388 like \f(CW\*(C`(?i:(?1))\*(C'\fR or \f(CW\*(C`(?:(?i)(?1))\*(C'\fR do not affect how the sub\-pattern will
2389 be processed.
2390 .ie n .IP """(?&\fINAME\fR)""" 4
2391 .el .IP \f(CW(?&\fR\f(CINAME\fR\f(CW)\fR 4
2392 .IX Xref "(?&NAME)"
2393 .IX Item "(?&NAME)"
2394 Recurse to a named subpattern. Identical to \f(CW\*(C`(?\fR\f(CIPARNO\fR\f(CW)\*(C'\fR except that the
2395 parenthesis to recurse to is determined by name. If multiple parentheses have
2396 the same name, then it recurses to the leftmost.
2397 .Sp
2398 It is an error to refer to a name that is not declared somewhere in the
2399 pattern.
2400 .Sp
2401 \&\fBNOTE:\fR In order to make things easier for programmers with experience
2402 with the Python or PCRE regex engines the pattern \f(CW\*(C`(?P>\fR\f(CINAME\fR\f(CW)\*(C'\fR
2403 may be used instead of \f(CW\*(C`(?&\fR\f(CINAME\fR\f(CW)\*(C'\fR.
2404 .ie n .IP """(?(\fIcondition\fR)\fIyes\-pattern\fR|\fIno\-pattern\fR)""" 4
2405 .el .IP \f(CW(?(\fR\f(CIcondition\fR\f(CW)\fR\f(CIyes\-pattern\fR\f(CW|\fR\f(CIno\-pattern\fR\f(CW)\fR 4
2406 .IX Xref "(?()"
2407 .IX Item "(?(condition)yes-pattern|no-pattern)"
2408 .PD 0
2409 .ie n .IP """(?(\fIcondition\fR)\fIyes\-pattern\fR)""" 4
2410 .el .IP \f(CW(?(\fR\f(CIcondition\fR\f(CW)\fR\f(CIyes\-pattern\fR\f(CW)\fR 4
2411 .IX Item "(?(condition)yes-pattern)"
2412 .PD
2413 Conditional expression. Matches \fIyes\-pattern\fR if \fIcondition\fR yields
2414 a true value, matches \fIno\-pattern\fR otherwise. A missing pattern always
2415 matches.
2416 .Sp
2417 \&\f(CW\*(C`(\fR\f(CIcondition\fR\f(CW)\*(C'\fR should be one of:
2418 .RS 4
2419 .IP "an integer in parentheses" 4
2420 .IX Item "an integer in parentheses"
2421 (which is valid if the corresponding pair of parentheses
2422 matched);
2423 .IP "a lookahead/lookbehind/evaluate zero\-width assertion;" 4
2424 .IX Item "a lookahead/lookbehind/evaluate zero-width assertion;"
2425 .PD 0
2426 .IP "a name in angle brackets or single quotes" 4
2427 .IX Item "a name in angle brackets or single quotes"
2428 .PD
2429 (which is valid if a group with the given name matched);
2430 .ie n .IP "the special symbol ""(R)""" 4
2431 .el .IP "the special symbol \f(CW(R)\fR" 4
2432 .IX Item "the special symbol (R)"
2433 (true when evaluated inside of recursion or eval). Additionally the
2434 \&\f(CW"R"\fR may be
2435 followed by a number, (which will be true when evaluated when recursing
2436 inside of the appropriate group), or by \f(CW\*(C`&\fR\f(CINAME\fR\f(CW\*(C'\fR, in which case it will
2437 be true only when evaluated during recursion in the named group.
2438 .RE
2439 .RS 4
2440 .Sp
2441 Here\*(Aqs a summary of the possible predicates:
2442 .ie n .IP """(1)"" ""(2)"" ..." 4
2443 .el .IP "\f(CW(1)\fR \f(CW(2)\fR ..." 4
2444 .IX Item "(1) (2) ..."
2445 Checks if the numbered capturing group has matched something.
2446 Full syntax: \f(CW\*(C`(?(1)then|else)\*(C'\fR
2447 .ie n .IP """(<\fINAME\fR>)"" ""(\*(Aq\fINAME\fR\*(Aq)""" 4
2448 .el .IP "\f(CW(<\fR\f(CINAME\fR\f(CW>)\fR \f(CW(\*(Aq\fR\f(CINAME\fR\f(CW\*(Aq)\fR" 4
2449 .IX Item "(<NAME>) ('NAME')"
2450 Checks if a group with the given name has matched something.
2451 Full syntax: \f(CW\*(C`(?(<name>)then|else)\*(C'\fR
2452 .ie n .IP """(?=...)"" ""(?!...)"" ""(?<=...)"" ""(?<!...)""" 4
2453 .el .IP "\f(CW(?=...)\fR \f(CW(?!...)\fR \f(CW(?<=...)\fR \f(CW(?<!...)\fR" 4
2454 .IX Item "(?=...) (?!...) (?<=...) (?<!...)"
2455 Checks whether the pattern matches (or does not match, for the \f(CW"!"\fR
2456 variants).
2457 Full syntax: \f(CW\*(C`(?(?=\fR\f(CIlookahead\fR\f(CW)\fR\f(CIthen\fR\f(CW|\fR\f(CIelse\fR\f(CW)\*(C'\fR
2458 .ie n .IP """(?{ \fICODE\fR })""" 4
2459 .el .IP "\f(CW(?{ \fR\f(CICODE\fR\f(CW })\fR" 4
2460 .IX Item "(?{ CODE })"
2461 Treats the return value of the code block as the condition.
2462 Full syntax: \f(CW\*(C`(?(?{ \fR\f(CICODE\fR\f(CW })\fR\f(CIthen\fR\f(CW|\fR\f(CIelse\fR\f(CW)\*(C'\fR
2463 .Sp
2464 Note use of this construct may globally affect the performance
2465 of the pattern. Consider using \f(CW\*(C`(*{ \fR\f(CICODE\fR\f(CW })\*(C'\fR
2466 .ie n .IP """(*{ \fICODE\fR })""" 4
2467 .el .IP "\f(CW(*{ \fR\f(CICODE\fR\f(CW })\fR" 4
2468 .IX Item "(*{ CODE })"
2469 Treats the return value of the code block as the condition.
2470 Full syntax: \f(CW\*(C`(?(*{ \fR\f(CICODE\fR\f(CW })\fR\f(CIthen\fR\f(CW|\fR\f(CIelse\fR\f(CW)\*(C'\fR
2471 .ie n .IP """(R)""" 4
2472 .el .IP \f(CW(R)\fR 4
2473 .IX Item "(R)"
2474 Checks if the expression has been evaluated inside of recursion.
2475 Full syntax: \f(CW\*(C`(?(R)\fR\f(CIthen\fR\f(CW|\fR\f(CIelse\fR\f(CW)\*(C'\fR
2476 .ie n .IP """(R1)"" ""(R2)"" ..." 4
2477 .el .IP "\f(CW(R1)\fR \f(CW(R2)\fR ..." 4
2478 .IX Item "(R1) (R2) ..."
2479 Checks if the expression has been evaluated while executing directly
2480 inside of the n\-th capture group. This check is the regex equivalent of
2481 .Sp
2482 .Vb 1
2483 \& if ((caller(0))[3] eq \*(Aqsubname\*(Aq) { ... }
2484 .Ve
2485 .Sp
2486 In other words, it does not check the full recursion stack.
2487 .Sp
2488 Full syntax: \f(CW\*(C`(?(R1)\fR\f(CIthen\fR\f(CW|\fR\f(CIelse\fR\f(CW)\*(C'\fR
2489 .ie n .IP """(R&\fINAME\fR)""" 4
2490 .el .IP \f(CW(R&\fR\f(CINAME\fR\f(CW)\fR 4
2491 .IX Item "(R&NAME)"
2492 Similar to \f(CW\*(C`(R1)\*(C'\fR, this predicate checks to see if we\*(Aqre executing
2493 directly inside of the leftmost group with a given name (this is the same
2494 logic used by \f(CW\*(C`(?&\fR\f(CINAME\fR\f(CW)\*(C'\fR to disambiguate). It does not check the full
2495 stack, but only the name of the innermost active recursion.
2496 Full syntax: \f(CW\*(C`(?(R&\fR\f(CIname\fR\f(CW)\fR\f(CIthen\fR\f(CW|\fR\f(CIelse\fR\f(CW)\*(C'\fR
2497 .ie n .IP """(DEFINE)""" 4
2498 .el .IP \f(CW(DEFINE)\fR 4
2499 .IX Item "(DEFINE)"
2500 In this case, the yes\-pattern is never directly executed, and no
2501 no\-pattern is allowed. Similar in spirit to \f(CW\*(C`(?{0})\*(C'\fR but more efficient.
2502 See below for details.
2503 Full syntax: \f(CW\*(C`(?(DEFINE)\fR\f(CIdefinitions\fR\f(CW...)\*(C'\fR
2504 .RE
2505 .RS 4
2506 .Sp
2507 For example:
2508 .Sp
2509 .Vb 4
2510 \& m{ ( \e( )?
2511 \& [^()]+
2512 \& (?(1) \e) )
2513 \& }x
2514 .Ve
2515 .Sp
2516 matches a chunk of non\-parentheses, possibly included in parentheses
2517 themselves.
2518 .Sp
2519 A special form is the \f(CW\*(C`(DEFINE)\*(C'\fR predicate, which never executes its
2520 yes\-pattern directly, and does not allow a no\-pattern. This allows one to
2521 define subpatterns which will be executed only by the recursion mechanism.
2522 This way, you can define a set of regular expression rules that can be
2523 bundled into any pattern you choose.
2524 .Sp
2525 It is recommended that for this usage you put the DEFINE block at the
2526 end of the pattern, and that you name any subpatterns defined within it.
2527 .Sp
2528 Also, it\*(Aqs worth noting that patterns defined this way probably will
2529 not be as efficient, as the optimizer is not very clever about
2530 handling them.
2531 .Sp
2532 An example of how this might be used is as follows:
2533 .Sp
2534 .Vb 5
2535 \& /(?<NAME>(?&NAME_PAT))(?<ADDR>(?&ADDRESS_PAT))
2536 \& (?(DEFINE)
2537 \& (?<NAME_PAT>....)
2538 \& (?<ADDRESS_PAT>....)
2539 \& )/x
2540 .Ve
2541 .Sp
2542 Note that capture groups matched inside of recursion are not accessible
2543 after the recursion returns, so the extra layer of capturing groups is
2544 necessary. Thus \f(CW$+{NAME_PAT}\fR would not be defined even though
2545 \&\f(CW$+{NAME}\fR would be.
2546 .Sp
2547 Finally, keep in mind that subpatterns created inside a DEFINE block
2548 count towards the absolute and relative number of captures, so this:
2549 .Sp
2550 .Vb 5
2551 \& my @captures = "a" =~ /(.) # First capture
2552 \& (?(DEFINE)
2553 \& (?<EXAMPLE> 1 ) # Second capture
2554 \& )/x;
2555 \& say scalar @captures;
2556 .Ve
2557 .Sp
2558 Will output 2, not 1. This is particularly important if you intend to
2559 compile the definitions with the \f(CW\*(C`qr//\*(C'\fR operator, and later
2560 interpolate them in another pattern.
2561 .RE
2562 .ie n .IP """(?>\fIpattern\fR)""" 4
2563 .el .IP \f(CW(?>\fR\f(CIpattern\fR\f(CW)\fR 4
2564 .IX Item "(?>pattern)"
2565 .PD 0
2566 .ie n .IP """(*atomic:\fIpattern\fR)""" 4
2567 .el .IP \f(CW(*atomic:\fR\f(CIpattern\fR\f(CW)\fR 4
2568 .IX Xref "(?>pattern) (*atomic backtrack backtracking atomic possessive"
2569 .IX Item "(*atomic:pattern)"
2570 .PD
2571 An "independent" subexpression, one which matches the substring
2572 that a standalone \fIpattern\fR would match if anchored at the given
2573 position, and it matches \fInothing other than this substring\fR. This
2574 construct is useful for optimizations of what would otherwise be
2575 "eternal" matches, because it will not backtrack (see "Backtracking").
2576 It may also be useful in places where the "grab all you can, and do not
2577 give anything back" semantic is desirable.
2578 .Sp
2579 For example: \f(CW\*(C`^(?>a*)ab\*(C'\fR will never match, since \f(CW\*(C`(?>a*)\*(C'\fR
2580 (anchored at the beginning of string, as above) will match \fIall\fR
2581 characters \f(CW"a"\fR at the beginning of string, leaving no \f(CW"a"\fR for
2582 \&\f(CW\*(C`ab\*(C'\fR to match. In contrast, \f(CW\*(C`a*ab\*(C'\fR will match the same as \f(CW\*(C`a+b\*(C'\fR,
2583 since the match of the subgroup \f(CW\*(C`a*\*(C'\fR is influenced by the following
2584 group \f(CW\*(C`ab\*(C'\fR (see "Backtracking"). In particular, \f(CW\*(C`a*\*(C'\fR inside
2585 \&\f(CW\*(C`a*ab\*(C'\fR will match fewer characters than a standalone \f(CW\*(C`a*\*(C'\fR, since
2586 this makes the tail match.
2587 .Sp
2588 \&\f(CW\*(C`(?>\fR\f(CIpattern\fR\f(CW)\*(C'\fR does not disable backtracking altogether once it has
2589 matched. It is still possible to backtrack past the construct, but not
2590 into it. So \f(CW\*(C`((?>a*)|(?>b*))ar\*(C'\fR will still match "bar".
2591 .Sp
2592 An effect similar to \f(CW\*(C`(?>\fR\f(CIpattern\fR\f(CW)\*(C'\fR may be achieved by writing
2593 \&\f(CW\*(C`(?=(\fR\f(CIpattern\fR\f(CW))\eg{\-1}\*(C'\fR. This matches the same substring as a standalone
2594 \&\f(CW\*(C`a+\*(C'\fR, and the following \f(CW\*(C`\eg{\-1}\*(C'\fR eats the matched string; it therefore
2595 makes a zero\-length assertion into an analogue of \f(CW\*(C`(?>...)\*(C'\fR.
2596 (The difference between these two constructs is that the second one
2597 uses a capturing group, thus shifting ordinals of backreferences
2598 in the rest of a regular expression.)
2599 .Sp
2600 Consider this pattern:
2601 .Sp
2602 .Vb 8
2603 \& m{ \e(
2604 \& (
2605 \& [^()]+ # x+
2606 \& |
2607 \& \e( [^()]* \e)
2608 \& )+
2609 \& \e)
2610 \& }x
2611 .Ve
2612 .Sp
2613 That will efficiently match a nonempty group with matching parentheses
2614 two levels deep or less. However, if there is no such group, it
2615 will take virtually forever on a long string. That\*(Aqs because there
2616 are so many different ways to split a long string into several
2617 substrings. This is what \f(CW\*(C`(.+)+\*(C'\fR is doing, and \f(CW\*(C`(.+)+\*(C'\fR is similar
2618 to a subpattern of the above pattern. Consider how the pattern
2619 above detects no\-match on \f(CW\*(C`((()aaaaaaaaaaaaaaaaaa\*(C'\fR in several
2620 seconds, but that each extra letter doubles this time. This
2621 exponential performance will make it appear that your program has
2622 hung. However, a tiny change to this pattern
2623 .Sp
2624 .Vb 8
2625 \& m{ \e(
2626 \& (
2627 \& (?> [^()]+ ) # change x+ above to (?> x+ )
2628 \& |
2629 \& \e( [^()]* \e)
2630 \& )+
2631 \& \e)
2632 \& }x
2633 .Ve
2634 .Sp
2635 which uses \f(CW\*(C`(?>...)\*(C'\fR matches exactly when the one above does (verifying
2636 this yourself would be a productive exercise), but finishes in a fourth
2637 the time when used on a similar string with 1000000 \f(CW"a"\fRs. Be aware,
2638 however, that, when this construct is followed by a
2639 quantifier, it currently triggers a warning message under
2640 the \f(CW\*(C`use warnings\*(C'\fR pragma or \fB\-w\fR switch saying it
2641 \&\f(CW"matches null string many times in regex"\fR.
2642 .Sp
2643 On simple groups, such as the pattern \f(CW\*(C`(?> [^()]+ )\*(C'\fR, a comparable
2644 effect may be achieved by negative lookahead, as in \f(CW\*(C`[^()]+ (?! [^()] )\*(C'\fR.
2645 This was only 4 times slower on a string with 1000000 \f(CW"a"\fRs.
2646 .Sp
2647 The "grab all you can, and do not give anything back" semantic is desirable
2648 in many situations where on the first sight a simple \f(CW\*(C`()*\*(C'\fR looks like
2649 the correct solution. Suppose we parse text with comments being delimited
2650 by \f(CW"#"\fR followed by some optional (horizontal) whitespace. Contrary to
2651 its appearance, \f(CW\*(C`#[ \et]*\*(C'\fR \fIis not\fR the correct subexpression to match
2652 the comment delimiter, because it may "give up" some whitespace if
2653 the remainder of the pattern can be made to match that way. The correct
2654 answer is either one of these:
2655 .Sp
2656 .Vb 2
2657 \& (?>#[ \et]*)
2658 \& #[ \et]*(?![ \et])
2659 .Ve
2660 .Sp
2661 For example, to grab non\-empty comments into \f(CW$1\fR, one should use either
2662 one of these:
2663 .Sp
2664 .Vb 2
2665 \& / (?> \e# [ \et]* ) ( .+ ) /x;
2666 \& / \e# [ \et]* ( [^ \et] .* ) /x;
2667 .Ve
2668 .Sp
2669 Which one you pick depends on which of these expressions better reflects
2670 the above specification of comments.
2671 .Sp
2672 In some literature this construct is called "atomic matching" or
2673 "possessive matching".
2674 .Sp
2675 Possessive quantifiers are equivalent to putting the item they are applied
2676 to inside of one of these constructs. The following equivalences apply:
2677 .Sp
2678 .Vb 6
2679 \& Quantifier Form Bracketing Form
2680 \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
2681 \& PAT*+ (?>PAT*)
2682 \& PAT++ (?>PAT+)
2683 \& PAT?+ (?>PAT?)
2684 \& PAT{min,max}+ (?>PAT{min,max})
2685 .Ve
2686 .Sp
2687 Nested \f(CW\*(C`(?>...)\*(C'\fR constructs are not no\-ops, even if at first glance
2688 they might seem to be. This is because the nested \f(CW\*(C`(?>...)\*(C'\fR can
2689 restrict internal backtracking that otherwise might occur. For example,
2690 .Sp
2691 .Vb 1
2692 \& "abc" =~ /(?>a[bc]*c)/
2693 .Ve
2694 .Sp
2695 matches, but
2696 .Sp
2697 .Vb 1
2698 \& "abc" =~ /(?>a(?>[bc]*)c)/
2699 .Ve
2700 .Sp
2701 does not.
2702 .ie n .IP """(?[ ])""" 4
2703 .el .IP "\f(CW(?[ ])\fR" 4
2704 .IX Item "(?[ ])"
2705 See "Extended Bracketed Character Classes" in perlrecharclass.
2706 .SS Backtracking
2707 .IX Xref "backtrack backtracking"
2708 .IX Subsection "Backtracking"
2709 NOTE: This section presents an abstract approximation of regular
2710 expression behavior. For a more rigorous (and complicated) view of
2711 the rules involved in selecting a match among possible alternatives,
2712 see "Combining RE Pieces".
2713 .PP
2714 A fundamental feature of regular expression matching involves the
2715 notion called \fIbacktracking\fR, which is currently used (when needed)
2716 by all regular non\-possessive expression quantifiers, namely \f(CW"*"\fR,
2717 \&\f(CW\*(C`*?\*(C'\fR, \f(CW"+"\fR, \f(CW\*(C`+?\*(C'\fR, \f(CW\*(C`{n,m}\*(C'\fR, and \f(CW\*(C`{n,m}?\*(C'\fR. Backtracking is often
2718 optimized internally, but the general principle outlined here is valid.
2719 .PP
2720 For a regular expression to match, the \fIentire\fR regular expression must
2721 match, not just part of it. So if the beginning of a pattern containing a
2722 quantifier succeeds in a way that causes later parts in the pattern to
2723 fail, the matching engine backs up and recalculates the beginning
2724 part\-\-that\*(Aqs why it\*(Aqs called backtracking.
2725 .PP
2726 Here is an example of backtracking: Let\*(Aqs say you want to find the
2727 word following "foo" in the string "Food is on the foo table.":
2728 .PP
2729 .Vb 4
2730 \& $_ = "Food is on the foo table.";
2731 \& if ( /\eb(foo)\es+(\ew+)/i ) {
2732 \& print "$2 follows $1.\en";
2733 \& }
2734 .Ve
2735 .PP
2736 When the match runs, the first part of the regular expression (\f(CW\*(C`\eb(foo)\*(C'\fR)
2737 finds a possible match right at the beginning of the string, and loads up
2738 \&\f(CW$1\fR with "Foo". However, as soon as the matching engine sees that there\*(Aqs
2739 no whitespace following the "Foo" that it had saved in \f(CW$1\fR, it realizes its
2740 mistake and starts over again one character after where it had the
2741 tentative match. This time it goes all the way until the next occurrence
2742 of "foo". The complete regular expression matches this time, and you get
2743 the expected output of "table follows foo."
2744 .PP
2745 Sometimes minimal matching can help a lot. Imagine you\*(Aqd like to match
2746 everything between "foo" and "bar". Initially, you write something
2747 like this:
2748 .PP
2749 .Vb 4
2750 \& $_ = "The food is under the bar in the barn.";
2751 \& if ( /foo(.*)bar/ ) {
2752 \& print "got <$1>\en";
2753 \& }
2754 .Ve
2755 .PP
2756 Which perhaps unexpectedly yields:
2757 .PP
2758 .Vb 1
2759 \& got <d is under the bar in the >
2760 .Ve
2761 .PP
2762 That\*(Aqs because \f(CW\*(C`.*\*(C'\fR was greedy, so you get everything between the
2763 \&\fIfirst\fR "foo" and the \fIlast\fR "bar". Here it\*(Aqs more effective
2764 to use minimal matching to make sure you get the text between a "foo"
2765 and the first "bar" thereafter.
2766 .PP
2767 .Vb 2
2768 \& if ( /foo(.*?)bar/ ) { print "got <$1>\en" }
2769 \& got <d is under the >
2770 .Ve
2771 .PP
2772 Here\*(Aqs another example. Let\*(Aqs say you\*(Aqd like to match a number at the end
2773 of a string, and you also want to keep the preceding part of the match.
2774 So you write this:
2775 .PP
2776 .Vb 4
2777 \& $_ = "I have 2 numbers: 53147";
2778 \& if ( /(.*)(\ed*)/ ) { # Wrong!
2779 \& print "Beginning is <$1>, number is <$2>.\en";
2780 \& }
2781 .Ve
2782 .PP
2783 That won\*(Aqt work at all, because \f(CW\*(C`.*\*(C'\fR was greedy and gobbled up the
2784 whole string. As \f(CW\*(C`\ed*\*(C'\fR can match on an empty string the complete
2785 regular expression matched successfully.
2786 .PP
2787 .Vb 1
2788 \& Beginning is <I have 2 numbers: 53147>, number is <>.
2789 .Ve
2790 .PP
2791 Here are some variants, most of which don\*(Aqt work:
2792 .PP
2793 .Vb 11
2794 \& $_ = "I have 2 numbers: 53147";
2795 \& @pats = qw{
2796 \& (.*)(\ed*)
2797 \& (.*)(\ed+)
2798 \& (.*?)(\ed*)
2799 \& (.*?)(\ed+)
2800 \& (.*)(\ed+)$
2801 \& (.*?)(\ed+)$
2802 \& (.*)\eb(\ed+)$
2803 \& (.*\eD)(\ed+)$
2804 \& };
2805 \&
2806 \& for $pat (@pats) {
2807 \& printf "%\-12s ", $pat;
2808 \& if ( /$pat/ ) {
2809 \& print "<$1> <$2>\en";
2810 \& } else {
2811 \& print "FAIL\en";
2812 \& }
2813 \& }
2814 .Ve
2815 .PP
2816 That will print out:
2817 .PP
2818 .Vb 8
2819 \& (.*)(\ed*) <I have 2 numbers: 53147> <>
2820 \& (.*)(\ed+) <I have 2 numbers: 5314> <7>
2821 \& (.*?)(\ed*) <> <>
2822 \& (.*?)(\ed+) <I have > <2>
2823 \& (.*)(\ed+)$ <I have 2 numbers: 5314> <7>
2824 \& (.*?)(\ed+)$ <I have 2 numbers: > <53147>
2825 \& (.*)\eb(\ed+)$ <I have 2 numbers: > <53147>
2826 \& (.*\eD)(\ed+)$ <I have 2 numbers: > <53147>
2827 .Ve
2828 .PP
2829 As you see, this can be a bit tricky. It\*(Aqs important to realize that a
2830 regular expression is merely a set of assertions that gives a definition
2831 of success. There may be 0, 1, or several different ways that the
2832 definition might succeed against a particular string. And if there are
2833 multiple ways it might succeed, you need to understand backtracking to
2834 know which variety of success you will achieve.
2835 .PP
2836 When using lookahead assertions and negations, this can all get even
2837 trickier. Imagine you\*(Aqd like to find a sequence of non\-digits not
2838 followed by "123". You might try to write that as
2839 .PP
2840 .Vb 4
2841 \& $_ = "ABC123";
2842 \& if ( /^\eD*(?!123)/ ) { # Wrong!
2843 \& print "Yup, no 123 in $_\en";
2844 \& }
2845 .Ve
2846 .PP
2847 But that isn\*(Aqt going to match; at least, not the way you\*(Aqre hoping. It
2848 claims that there is no 123 in the string. Here\*(Aqs a clearer picture of
2849 why that pattern matches, contrary to popular expectations:
2850 .PP
2851 .Vb 2
2852 \& $x = \*(AqABC123\*(Aq;
2853 \& $y = \*(AqABC445\*(Aq;
2854 \&
2855 \& print "1: got $1\en" if $x =~ /^(ABC)(?!123)/;
2856 \& print "2: got $1\en" if $y =~ /^(ABC)(?!123)/;
2857 \&
2858 \& print "3: got $1\en" if $x =~ /^(\eD*)(?!123)/;
2859 \& print "4: got $1\en" if $y =~ /^(\eD*)(?!123)/;
2860 .Ve
2861 .PP
2862 This prints
2863 .PP
2864 .Vb 3
2865 \& 2: got ABC
2866 \& 3: got AB
2867 \& 4: got ABC
2868 .Ve
2869 .PP
2870 You might have expected test 3 to fail because it seems to a more
2871 general purpose version of test 1. The important difference between
2872 them is that test 3 contains a quantifier (\f(CW\*(C`\eD*\*(C'\fR) and so can use
2873 backtracking, whereas test 1 will not. What\*(Aqs happening is
2874 that you\*(Aqve asked "Is it true that at the start of \f(CW$x\fR, following 0 or more
2875 non\-digits, you have something that\*(Aqs not 123?" If the pattern matcher had
2876 let \f(CW\*(C`\eD*\*(C'\fR expand to "ABC", this would have caused the whole pattern to
2877 fail.
2878 .PP
2879 The search engine will initially match \f(CW\*(C`\eD*\*(C'\fR with "ABC". Then it will
2880 try to match \f(CW\*(C`(?!123)\*(C'\fR with "123", which fails. But because
2881 a quantifier (\f(CW\*(C`\eD*\*(C'\fR) has been used in the regular expression, the
2882 search engine can backtrack and retry the match differently
2883 in the hope of matching the complete regular expression.
2884 .PP
2885 The pattern really, \fIreally\fR wants to succeed, so it uses the
2886 standard pattern back\-off\-and\-retry and lets \f(CW\*(C`\eD*\*(C'\fR expand to just "AB" this
2887 time. Now there\*(Aqs indeed something following "AB" that is not
2888 "123". It\*(Aqs "C123", which suffices.
2889 .PP
2890 We can deal with this by using both an assertion and a negation.
2891 We\*(Aqll say that the first part in \f(CW$1\fR must be followed both by a digit
2892 and by something that\*(Aqs not "123". Remember that the lookaheads
2893 are zero\-width expressions\-\-they only look, but don\*(Aqt consume any
2894 of the string in their match. So rewriting this way produces what
2895 you\*(Aqd expect; that is, case 5 will fail, but case 6 succeeds:
2896 .PP
2897 .Vb 2
2898 \& print "5: got $1\en" if $x =~ /^(\eD*)(?=\ed)(?!123)/;
2899 \& print "6: got $1\en" if $y =~ /^(\eD*)(?=\ed)(?!123)/;
2900 \&
2901 \& 6: got ABC
2902 .Ve
2903 .PP
2904 In other words, the two zero\-width assertions next to each other work as though
2905 they\*(Aqre ANDed together, just as you\*(Aqd use any built\-in assertions: \f(CW\*(C`/^$/\*(C'\fR
2906 matches only if you\*(Aqre at the beginning of the line AND the end of the
2907 line simultaneously. The deeper underlying truth is that juxtaposition in
2908 regular expressions always means AND, except when you write an explicit OR
2909 using the vertical bar. \f(CW\*(C`/ab/\*(C'\fR means match "a" AND (then) match "b",
2910 although the attempted matches are made at different positions because "a"
2911 is not a zero\-width assertion, but a one\-width assertion.
2912 .PP
2913 \&\fBWARNING\fR: Particularly complicated regular expressions can take
2914 exponential time to solve because of the immense number of possible
2915 ways they can use backtracking to try for a match. For example, without
2916 internal optimizations done by the regular expression engine, this will
2917 take a painfully long time to run:
2918 .PP
2919 .Vb 1
2920 \& \*(Aqaaaaaaaaaaaa\*(Aq =~ /((a{0,5}){0,5})*[c]/
2921 .Ve
2922 .PP
2923 And if you used \f(CW"*"\fR\*(Aqs in the internal groups instead of limiting them
2924 to 0 through 5 matches, then it would take forever\-\-or until you ran
2925 out of stack space. Moreover, these internal optimizations are not
2926 always applicable. For example, if you put \f(CW\*(C`{0,5}\*(C'\fR instead of \f(CW"*"\fR
2927 on the external group, no current optimization is applicable, and the
2928 match takes a long time to finish.
2929 .PP
2930 A powerful tool for optimizing such beasts is what is known as an
2931 "independent group",
2932 which does not backtrack (see \f(CW"(?>pattern)"\fR). Note also that
2933 zero\-length lookahead/lookbehind assertions will not backtrack to make
2934 the tail match, since they are in "logical" context: only
2935 whether they match is considered relevant. For an example
2936 where side\-effects of lookahead \fImight\fR have influenced the
2937 following match, see \f(CW"(?>pattern)"\fR.
2938 .SS "Script Runs"
2939 .IX Xref "(*script_run:...) (sr:...) (*atomic_script_run:...) (asr:...)"
2940 .IX Subsection "Script Runs"
2941 A script run is basically a sequence of characters, all from the same
2942 Unicode script (see "Scripts" in perlunicode), such as Latin or Greek. In
2943 most places a single word would never be written in multiple scripts,
2944 unless it is a spoofing attack. An infamous example, is
2945 .PP
2946 .Vb 1
2947 \& paypal.com
2948 .Ve
2949 .PP
2950 Those letters could all be Latin (as in the example just above), or they
2951 could be all Cyrillic (except for the dot), or they could be a mixture
2952 of the two. In the case of an internet address the \f(CW\*(C`.com\*(C'\fR would be in
2953 Latin, And any Cyrillic ones would cause it to be a mixture, not a
2954 script run. Someone clicking on such a link would not be directed to
2955 the real PayPal website, but an attacker would craft a look\-alike one to
2956 attempt to gather sensitive information from the person.
2957 .PP
2958 Starting in Perl 5.28, it is now easy to detect strings that aren\*(Aqt
2959 script runs. Simply enclose just about any pattern like either of
2960 these:
2961 .PP
2962 .Vb 2
2963 \& (*script_run:pattern)
2964 \& (*sr:pattern)
2965 .Ve
2966 .PP
2967 What happens is that after \fIpattern\fR succeeds in matching, it is
2968 subjected to the additional criterion that every character in it must be
2969 from the same script (see exceptions below). If this isn\*(Aqt true,
2970 backtracking occurs until something all in the same script is found that
2971 matches, or all possibilities are exhausted. This can cause a lot of
2972 backtracking, but generally, only malicious input will result in this,
2973 though the slow down could cause a denial of service attack. If your
2974 needs permit, it is best to make the pattern atomic to cut down on the
2975 amount of backtracking. This is so likely to be what you want, that
2976 instead of writing this:
2977 .PP
2978 .Vb 1
2979 \& (*script_run:(?>pattern))
2980 .Ve
2981 .PP
2982 you can write either of these:
2983 .PP
2984 .Vb 2
2985 \& (*atomic_script_run:pattern)
2986 \& (*asr:pattern)
2987 .Ve
2988 .PP
2989 (See \f(CW"(?>\fR\f(CIpattern\fR\f(CW)"\fR.)
2990 .PP
2991 In Taiwan, Japan, and Korea, it is common for text to have a mixture of
2992 characters from their native scripts and base Chinese. Perl follows
2993 Unicode\*(Aqs UTS 39 (<https://unicode.org/reports/tr39/>) Unicode Security
2994 Mechanisms in allowing such mixtures. For example, the Japanese scripts
2995 Katakana and Hiragana are commonly mixed together in practice, along
2996 with some Chinese characters, and hence are treated as being in a single
2997 script run by Perl.
2998 .PP
2999 The rules used for matching decimal digits are slightly stricter. Many
3000 scripts have their own sets of digits equivalent to the Western \f(CW0\fR
3001 through \f(CW9\fR ones. A few, such as Arabic, have more than one set. For
3002 a string to be considered a script run, all digits in it must come from
3003 the same set of ten, as determined by the first digit encountered.
3004 As an example,
3005 .PP
3006 .Vb 1
3007 \& qr/(*script_run: \ed+ \eb )/x
3008 .Ve
3009 .PP
3010 guarantees that the digits matched will all be from the same set of 10.
3011 You won\*(Aqt get a look\-alike digit from a different script that has a
3012 different value than what it appears to be.
3013 .PP
3014 Unicode has three pseudo scripts that are handled specially.
3015 .PP
3016 "Unknown" is applied to code points whose meaning has yet to be
3017 determined. Perl currently will match as a script run, any single
3018 character string consisting of one of these code points. But any string
3019 longer than one code point containing one of these will not be
3020 considered a script run.
3021 .PP
3022 "Inherited" is applied to characters that modify another, such as an
3023 accent of some type. These are considered to be in the script of the
3024 master character, and so never cause a script run to not match.
3025 .PP
3026 The other one is "Common". This consists of mostly punctuation, emoji,
3027 characters used in mathematics and music, the ASCII digits \f(CW0\fR
3028 through \f(CW9\fR, and full\-width forms of these digits. These characters
3029 can appear intermixed in text in many of the world\*(Aqs scripts. These
3030 also don\*(Aqt cause a script run to not match. But like other scripts, all
3031 digits in a run must come from the same set of 10.
3032 .PP
3033 This construct is non\-capturing. You can add parentheses to \fIpattern\fR
3034 to capture, if desired. You will have to do this if you plan to use
3035 "(*ACCEPT) (*ACCEPT:arg)" and not have it bypass the script run
3036 checking.
3037 .PP
3038 The \f(CW\*(C`Script_Extensions\*(C'\fR property as modified by UTS 39
3039 (<https://unicode.org/reports/tr39/>) is used as the basis for this
3040 feature.
3041 .PP
3042 To summarize,
3043 .IP \(bu 4
3044 All length 0 or length 1 sequences are script runs.
3045 .IP \(bu 4
3046 A longer sequence is a script run if and only if \fBall\fR of the following
3047 conditions are met:
3048 .Sp
3049
3050 .RS 4
3051 .IP 1. 4
3052 No code point in the sequence has the \f(CW\*(C`Script_Extension\*(C'\fR property of
3053 \&\f(CW\*(C`Unknown\*(C'\fR.
3054 .Sp
3055 This currently means that all code points in the sequence have been
3056 assigned by Unicode to be characters that aren\*(Aqt private use nor
3057 surrogate code points.
3058 .IP 2. 4
3059 All characters in the sequence come from the Common script and/or the
3060 Inherited script and/or a single other script.
3061 .Sp
3062 The script of a character is determined by the \f(CW\*(C`Script_Extensions\*(C'\fR
3063 property as modified by UTS 39 (<https://unicode.org/reports/tr39/>), as
3064 described above.
3065 .IP 3. 4
3066 All decimal digits in the sequence come from the same block of 10
3067 consecutive digits.
3068 .RE
3069 .RS 4
3070 .RE
3071 .SS "Special Backtracking Control Verbs"
3072 .IX Subsection "Special Backtracking Control Verbs"
3073 These special patterns are generally of the form \f(CW\*(C`(*\fR\f(CIVERB\fR\f(CW:\fR\f(CIarg\fR\f(CW)\*(C'\fR. Unless
3074 otherwise stated the \fIarg\fR argument is optional; in some cases, it is
3075 mandatory.
3076 .PP
3077 Any pattern containing a special backtracking verb that allows an argument
3078 has the special behaviour that when executed it sets the current package\*(Aqs
3079 \&\f(CW$REGERROR\fR and \f(CW$REGMARK\fR variables. When doing so the following
3080 rules apply:
3081 .PP
3082 On failure, the \f(CW$REGERROR\fR variable will be set to the \fIarg\fR value of the
3083 verb pattern, if the verb was involved in the failure of the match. If the
3084 \&\fIarg\fR part of the pattern was omitted, then \f(CW$REGERROR\fR will be set to the
3085 name of the last \f(CW\*(C`(*MARK:\fR\f(CINAME\fR\f(CW)\*(C'\fR pattern executed, or to TRUE if there was
3086 none. Also, the \f(CW$REGMARK\fR variable will be set to FALSE.
3087 .PP
3088 On a successful match, the \f(CW$REGERROR\fR variable will be set to FALSE, and
3089 the \f(CW$REGMARK\fR variable will be set to the name of the last
3090 \&\f(CW\*(C`(*MARK:\fR\f(CINAME\fR\f(CW)\*(C'\fR pattern executed. See the explanation for the
3091 \&\f(CW\*(C`(*MARK:\fR\f(CINAME\fR\f(CW)\*(C'\fR verb below for more details.
3092 .PP
3093 \&\fBNOTE:\fR \f(CW$REGERROR\fR and \f(CW$REGMARK\fR are not magic variables like \f(CW$1\fR
3094 and most other regex\-related variables. They are not local to a scope, nor
3095 readonly, but instead are volatile package variables similar to \f(CW$AUTOLOAD\fR.
3096 They are set in the package containing the code that \fIexecuted\fR the regex
3097 (rather than the one that compiled it, where those differ). If necessary, you
3098 can use \f(CW\*(C`local\*(C'\fR to localize changes to these variables to a specific scope
3099 before executing a regex.
3100 .PP
3101 If a pattern does not contain a special backtracking verb that allows an
3102 argument, then \f(CW$REGERROR\fR and \f(CW$REGMARK\fR are not touched at all.
3103 .IP Verbs 3
3104 .IX Item "Verbs"
3105 .RS 3
3106 .PD 0
3107 .ie n .IP """(*PRUNE)"" ""(*PRUNE:\fINAME\fR)""" 4
3108 .el .IP "\f(CW(*PRUNE)\fR \f(CW(*PRUNE:\fR\f(CINAME\fR\f(CW)\fR" 4
3109 .IX Xref "(*PRUNE) (*PRUNE:NAME)"
3110 .IX Item "(*PRUNE) (*PRUNE:NAME)"
3111 .PD
3112 This zero\-width pattern prunes the backtracking tree at the current point
3113 when backtracked into on failure. Consider the pattern \f(CW\*(C`/\fR\f(CIA\fR\f(CW (*PRUNE) \fR\f(CIB\fR\f(CW/\*(C'\fR,
3114 where \fIA\fR and \fIB\fR are complex patterns. Until the \f(CW\*(C`(*PRUNE)\*(C'\fR verb is reached,
3115 \&\fIA\fR may backtrack as necessary to match. Once it is reached, matching
3116 continues in \fIB\fR, which may also backtrack as necessary; however, should B
3117 not match, then no further backtracking will take place, and the pattern
3118 will fail outright at the current starting position.
3119 .Sp
3120 The following example counts all the possible matching strings in a
3121 pattern (without actually matching any of them).
3122 .Sp
3123 .Vb 2
3124 \& \*(Aqaaab\*(Aq =~ /a+b?(?{print "$&\en"; $count++})(*FAIL)/;
3125 \& print "Count=$count\en";
3126 .Ve
3127 .Sp
3128 which produces:
3129 .Sp
3130 .Vb 10
3131 \& aaab
3132 \& aaa
3133 \& aa
3134 \& a
3135 \& aab
3136 \& aa
3137 \& a
3138 \& ab
3139 \& a
3140 \& Count=9
3141 .Ve
3142 .Sp
3143 If we add a \f(CW\*(C`(*PRUNE)\*(C'\fR before the count like the following
3144 .Sp
3145 .Vb 2
3146 \& \*(Aqaaab\*(Aq =~ /a+b?(*PRUNE)(?{print "$&\en"; $count++})(*FAIL)/;
3147 \& print "Count=$count\en";
3148 .Ve
3149 .Sp
3150 we prevent backtracking and find the count of the longest matching string
3151 at each matching starting point like so:
3152 .Sp
3153 .Vb 4
3154 \& aaab
3155 \& aab
3156 \& ab
3157 \& Count=3
3158 .Ve
3159 .Sp
3160 Any number of \f(CW\*(C`(*PRUNE)\*(C'\fR assertions may be used in a pattern.
3161 .Sp
3162 See also \f(CW"(?>\fR\f(CIpattern\fR\f(CW)"\fR and possessive quantifiers for
3163 other ways to
3164 control backtracking. In some cases, the use of \f(CW\*(C`(*PRUNE)\*(C'\fR can be
3165 replaced with a \f(CW\*(C`(?>pattern)\*(C'\fR with no functional difference; however,
3166 \&\f(CW\*(C`(*PRUNE)\*(C'\fR can be used to handle cases that cannot be expressed using a
3167 \&\f(CW\*(C`(?>pattern)\*(C'\fR alone.
3168 .ie n .IP """(*SKIP)"" ""(*SKIP:\fINAME\fR)""" 4
3169 .el .IP "\f(CW(*SKIP)\fR \f(CW(*SKIP:\fR\f(CINAME\fR\f(CW)\fR" 4
3170 .IX Xref "(*SKIP)"
3171 .IX Item "(*SKIP) (*SKIP:NAME)"
3172 This zero\-width pattern is similar to \f(CW\*(C`(*PRUNE)\*(C'\fR, except that on
3173 failure it also signifies that whatever text that was matched leading up
3174 to the \f(CW\*(C`(*SKIP)\*(C'\fR pattern being executed cannot be part of \fIany\fR match
3175 of this pattern. This effectively means that the regex engine "skips" forward
3176 to this position on failure and tries to match again, (assuming that
3177 there is sufficient room to match).
3178 .Sp
3179 The name of the \f(CW\*(C`(*SKIP:\fR\f(CINAME\fR\f(CW)\*(C'\fR pattern has special significance. If a
3180 \&\f(CW\*(C`(*MARK:\fR\f(CINAME\fR\f(CW)\*(C'\fR was encountered while matching, then it is that position
3181 which is used as the "skip point". If no \f(CW\*(C`(*MARK)\*(C'\fR of that name was
3182 encountered, then the \f(CW\*(C`(*SKIP)\*(C'\fR operator has no effect. When used
3183 without a name the "skip point" is where the match point was when
3184 executing the \f(CW\*(C`(*SKIP)\*(C'\fR pattern.
3185 .Sp
3186 Compare the following to the examples in \f(CW\*(C`(*PRUNE)\*(C'\fR; note the string
3187 is twice as long:
3188 .Sp
3189 .Vb 2
3190 \& \*(Aqaaabaaab\*(Aq =~ /a+b?(*SKIP)(?{print "$&\en"; $count++})(*FAIL)/;
3191 \& print "Count=$count\en";
3192 .Ve
3193 .Sp
3194 outputs
3195 .Sp
3196 .Vb 3
3197 \& aaab
3198 \& aaab
3199 \& Count=2
3200 .Ve
3201 .Sp
3202 Once the \*(Aqaaab\*(Aq at the start of the string has matched, and the \f(CW\*(C`(*SKIP)\*(C'\fR
3203 executed, the next starting point will be where the cursor was when the
3204 \&\f(CW\*(C`(*SKIP)\*(C'\fR was executed.
3205 .ie n .IP """(*MARK:\fINAME\fR)"" ""(*:\fINAME\fR)""" 4
3206 .el .IP "\f(CW(*MARK:\fR\f(CINAME\fR\f(CW)\fR \f(CW(*:\fR\f(CINAME\fR\f(CW)\fR" 4
3207 .IX Xref "(*MARK) (*MARK:NAME) (*:NAME)"
3208 .IX Item "(*MARK:NAME) (*:NAME)"
3209 This zero\-width pattern can be used to mark the point reached in a string
3210 when a certain part of the pattern has been successfully matched. This
3211 mark may be given a name. A later \f(CW\*(C`(*SKIP)\*(C'\fR pattern will then skip
3212 forward to that point if backtracked into on failure. Any number of
3213 \&\f(CW\*(C`(*MARK)\*(C'\fR patterns are allowed, and the \fINAME\fR portion may be duplicated.
3214 .Sp
3215 In addition to interacting with the \f(CW\*(C`(*SKIP)\*(C'\fR pattern, \f(CW\*(C`(*MARK:\fR\f(CINAME\fR\f(CW)\*(C'\fR
3216 can be used to "label" a pattern branch, so that after matching, the
3217 program can determine which branches of the pattern were involved in the
3218 match.
3219 .Sp
3220 When a match is successful, the \f(CW$REGMARK\fR variable will be set to the
3221 name of the most recently executed \f(CW\*(C`(*MARK:\fR\f(CINAME\fR\f(CW)\*(C'\fR that was involved
3222 in the match.
3223 .Sp
3224 This can be used to determine which branch of a pattern was matched
3225 without using a separate capture group for each branch, which in turn
3226 can result in a performance improvement, as perl cannot optimize
3227 \&\f(CW\*(C`/(?:(x)|(y)|(z))/\*(C'\fR as efficiently as something like
3228 \&\f(CW\*(C`/(?:x(*MARK:x)|y(*MARK:y)|z(*MARK:z))/\*(C'\fR.
3229 .Sp
3230 When a match has failed, and unless another verb has been involved in
3231 failing the match and has provided its own name to use, the \f(CW$REGERROR\fR
3232 variable will be set to the name of the most recently executed
3233 \&\f(CW\*(C`(*MARK:\fR\f(CINAME\fR\f(CW)\*(C'\fR.
3234 .Sp
3235 See "(*SKIP)" for more details.
3236 .Sp
3237 As a shortcut \f(CW\*(C`(*MARK:\fR\f(CINAME\fR\f(CW)\*(C'\fR can be written \f(CW\*(C`(*:\fR\f(CINAME\fR\f(CW)\*(C'\fR.
3238 .ie n .IP """(*THEN)"" ""(*THEN:\fINAME\fR)""" 4
3239 .el .IP "\f(CW(*THEN)\fR \f(CW(*THEN:\fR\f(CINAME\fR\f(CW)\fR" 4
3240 .IX Item "(*THEN) (*THEN:NAME)"
3241 This is similar to the "cut group" operator \f(CW\*(C`::\*(C'\fR from Raku. Like
3242 \&\f(CW\*(C`(*PRUNE)\*(C'\fR, this verb always matches, and when backtracked into on
3243 failure, it causes the regex engine to try the next alternation in the
3244 innermost enclosing group (capturing or otherwise) that has alternations.
3245 The two branches of a \f(CW\*(C`(?(\fR\f(CIcondition\fR\f(CW)\fR\f(CIyes\-pattern\fR\f(CW|\fR\f(CIno\-pattern\fR\f(CW)\*(C'\fR do not
3246 count as an alternation, as far as \f(CW\*(C`(*THEN)\*(C'\fR is concerned.
3247 .Sp
3248 Its name comes from the observation that this operation combined with the
3249 alternation operator (\f(CW"|"\fR) can be used to create what is essentially a
3250 pattern\-based if/then/else block:
3251 .Sp
3252 .Vb 1
3253 \& ( COND (*THEN) FOO | COND2 (*THEN) BAR | COND3 (*THEN) BAZ )
3254 .Ve
3255 .Sp
3256 Note that if this operator is used and NOT inside of an alternation then
3257 it acts exactly like the \f(CW\*(C`(*PRUNE)\*(C'\fR operator.
3258 .Sp
3259 .Vb 1
3260 \& / A (*PRUNE) B /
3261 .Ve
3262 .Sp
3263 is the same as
3264 .Sp
3265 .Vb 1
3266 \& / A (*THEN) B /
3267 .Ve
3268 .Sp
3269 but
3270 .Sp
3271 .Vb 1
3272 \& / ( A (*THEN) B | C ) /
3273 .Ve
3274 .Sp
3275 is not the same as
3276 .Sp
3277 .Vb 1
3278 \& / ( A (*PRUNE) B | C ) /
3279 .Ve
3280 .Sp
3281 as after matching the \fIA\fR but failing on the \fIB\fR the \f(CW\*(C`(*THEN)\*(C'\fR verb will
3282 backtrack and try \fIC\fR; but the \f(CW\*(C`(*PRUNE)\*(C'\fR verb will simply fail.
3283 .ie n .IP """(*COMMIT)"" ""(*COMMIT:\fIarg\fR)""" 4
3284 .el .IP "\f(CW(*COMMIT)\fR \f(CW(*COMMIT:\fR\f(CIarg\fR\f(CW)\fR" 4
3285 .IX Xref "(*COMMIT)"
3286 .IX Item "(*COMMIT) (*COMMIT:arg)"
3287 This is the Raku "commit pattern" \f(CW\*(C`<commit>\*(C'\fR or \f(CW\*(C`:::\*(C'\fR. It\*(Aqs a
3288 zero\-width pattern similar to \f(CW\*(C`(*SKIP)\*(C'\fR, except that when backtracked
3289 into on failure it causes the match to fail outright. No further attempts
3290 to find a valid match by advancing the start pointer will occur again.
3291 For example,
3292 .Sp
3293 .Vb 2
3294 \& \*(Aqaaabaaab\*(Aq =~ /a+b?(*COMMIT)(?{print "$&\en"; $count++})(*FAIL)/;
3295 \& print "Count=$count\en";
3296 .Ve
3297 .Sp
3298 outputs
3299 .Sp
3300 .Vb 2
3301 \& aaab
3302 \& Count=1
3303 .Ve
3304 .Sp
3305 In other words, once the \f(CW\*(C`(*COMMIT)\*(C'\fR has been entered, and if the pattern
3306 does not match, the regex engine will not try any further matching on the
3307 rest of the string.
3308 .ie n .IP """(*FAIL)"" ""(*F)"" ""(*FAIL:\fIarg\fR)""" 4
3309 .el .IP "\f(CW(*FAIL)\fR \f(CW(*F)\fR \f(CW(*FAIL:\fR\f(CIarg\fR\f(CW)\fR" 4
3310 .IX Xref "(*FAIL) (*F)"
3311 .IX Item "(*FAIL) (*F) (*FAIL:arg)"
3312 This pattern matches nothing and always fails. It can be used to force the
3313 engine to backtrack. It is equivalent to \f(CW\*(C`(?!)\*(C'\fR, but easier to read. In
3314 fact, \f(CW\*(C`(?!)\*(C'\fR gets optimised into \f(CW\*(C`(*FAIL)\*(C'\fR internally. You can provide
3315 an argument so that if the match fails because of this \f(CW\*(C`FAIL\*(C'\fR directive
3316 the argument can be obtained from \f(CW$REGERROR\fR.
3317 .Sp
3318 It is probably useful only when combined with \f(CW\*(C`(?{})\*(C'\fR or \f(CW\*(C`(??{})\*(C'\fR.
3319 .ie n .IP """(*ACCEPT)"" ""(*ACCEPT:\fIarg\fR)""" 4
3320 .el .IP "\f(CW(*ACCEPT)\fR \f(CW(*ACCEPT:\fR\f(CIarg\fR\f(CW)\fR" 4
3321 .IX Xref "(*ACCEPT)"
3322 .IX Item "(*ACCEPT) (*ACCEPT:arg)"
3323 This pattern matches nothing and causes the end of successful matching at
3324 the point at which the \f(CW\*(C`(*ACCEPT)\*(C'\fR pattern was encountered, regardless of
3325 whether there is actually more to match in the string. When inside of a
3326 nested pattern, such as recursion, or in a subpattern dynamically generated
3327 via \f(CW\*(C`(??{})\*(C'\fR, only the innermost pattern is ended immediately.
3328 .Sp
3329 If the \f(CW\*(C`(*ACCEPT)\*(C'\fR is inside of capturing groups then the groups are
3330 marked as ended at the point at which the \f(CW\*(C`(*ACCEPT)\*(C'\fR was encountered.
3331 For instance:
3332 .Sp
3333 .Vb 1
3334 \& \*(AqAB\*(Aq =~ /(A (A|B(*ACCEPT)|C) D)(E)/x;
3335 .Ve
3336 .Sp
3337 will match, and \f(CW$1\fR will be \f(CW\*(C`AB\*(C'\fR and \f(CW$2\fR will be \f(CW"B"\fR, \f(CW$3\fR will not
3338 be set. If another branch in the inner parentheses was matched, such as in the
3339 string \*(AqACDE\*(Aq, then the \f(CW"D"\fR and \f(CW"E"\fR would have to be matched as well.
3340 .Sp
3341 You can provide an argument, which will be available in the var
3342 \&\f(CW$REGMARK\fR after the match completes.
3343 .RE
3344 .RS 3
3345 .RE
3346 .ie n .SS "Warning on ""\e1"" Instead of $1"
3347 .el .SS "Warning on \f(CW\e1\fP Instead of \f(CW$1\fP"
3348 .IX Subsection "Warning on 1 Instead of $1"
3349 Some people get too used to writing things like:
3350 .PP
3351 .Vb 1
3352 \& $pattern =~ s/(\eW)/\e\e\e1/g;
3353 .Ve
3354 .PP
3355 This is grandfathered (for \e1 to \e9) for the RHS of a substitute to avoid
3356 shocking the
3357 \&\fBsed\fR addicts, but it\*(Aqs a dirty habit to get into. That\*(Aqs because in
3358 PerlThink, the righthand side of an \f(CW\*(C`s///\*(C'\fR is a double\-quoted string. \f(CW\*(C`\e1\*(C'\fR in
3359 the usual double\-quoted string means a control\-A. The customary Unix
3360 meaning of \f(CW\*(C`\e1\*(C'\fR is kludged in for \f(CW\*(C`s///\*(C'\fR. However, if you get into the habit
3361 of doing that, you get yourself into trouble if you then add an \f(CW\*(C`/e\*(C'\fR
3362 modifier.
3363 .PP
3364 .Vb 1
3365 \& s/(\ed+)/ \e1 + 1 /eg; # causes warning under \-w
3366 .Ve
3367 .PP
3368 Or if you try to do
3369 .PP
3370 .Vb 1
3371 \& s/(\ed+)/\e1000/;
3372 .Ve
3373 .PP
3374 You can\*(Aqt disambiguate that by saying \f(CW\*(C`\e{1}000\*(C'\fR, whereas you can fix it with
3375 \&\f(CW\*(C`${1}000\*(C'\fR. The operation of interpolation should not be confused
3376 with the operation of matching a backreference. Certainly they mean two
3377 different things on the \fIleft\fR side of the \f(CW\*(C`s///\*(C'\fR.
3378 .SS "Repeated Patterns Matching a Zero\-length Substring"
3379 .IX Subsection "Repeated Patterns Matching a Zero-length Substring"
3380 \&\fBWARNING\fR: Difficult material (and prose) ahead. This section needs a rewrite.
3381 .PP
3382 Regular expressions provide a terse and powerful programming language. As
3383 with most other power tools, power comes together with the ability
3384 to wreak havoc.
3385 .PP
3386 A common abuse of this power stems from the ability to make infinite
3387 loops using regular expressions, with something as innocuous as:
3388 .PP
3389 .Vb 1
3390 \& \*(Aqfoo\*(Aq =~ m{ ( o? )* }x;
3391 .Ve
3392 .PP
3393 The \f(CW\*(C`o?\*(C'\fR matches at the beginning of "\f(CW\*(C`foo\*(C'\fR", and since the position
3394 in the string is not moved by the match, \f(CW\*(C`o?\*(C'\fR would match again and again
3395 because of the \f(CW"*"\fR quantifier. Another common way to create a similar cycle
3396 is with the looping modifier \f(CW\*(C`/g\*(C'\fR:
3397 .PP
3398 .Vb 1
3399 \& @matches = ( \*(Aqfoo\*(Aq =~ m{ o? }xg );
3400 .Ve
3401 .PP
3402 or
3403 .PP
3404 .Vb 1
3405 \& print "match: <$&>\en" while \*(Aqfoo\*(Aq =~ m{ o? }xg;
3406 .Ve
3407 .PP
3408 or the loop implied by \f(CWsplit()\fR.
3409 .PP
3410 However, long experience has shown that many programming tasks may
3411 be significantly simplified by using repeated subexpressions that
3412 may match zero\-length substrings. Here\*(Aqs a simple example being:
3413 .PP
3414 .Vb 2
3415 \& @chars = split //, $string; # // is not magic in split
3416 \& ($whitewashed = $string) =~ s/()/ /g; # parens avoid magic s// /
3417 .Ve
3418 .PP
3419 Thus Perl allows such constructs, by \fIforcefully breaking
3420 the infinite loop\fR. The rules for this are different for lower\-level
3421 loops given by the greedy quantifiers \f(CW\*(C`*+{}\*(C'\fR, and for higher\-level
3422 ones like the \f(CW\*(C`/g\*(C'\fR modifier or \f(CWsplit()\fR operator.
3423 .PP
3424 The lower\-level loops are \fIinterrupted\fR (that is, the loop is
3425 broken) when Perl detects that a repeated expression matched a
3426 zero\-length substring. Thus
3427 .PP
3428 .Vb 1
3429 \& m{ (?: NON_ZERO_LENGTH | ZERO_LENGTH )* }x;
3430 .Ve
3431 .PP
3432 is made equivalent to
3433 .PP
3434 .Vb 1
3435 \& m{ (?: NON_ZERO_LENGTH )* (?: ZERO_LENGTH )? }x;
3436 .Ve
3437 .PP
3438 For example, this program
3439 .PP
3440 .Vb 12
3441 \& #!perl \-l
3442 \& "aaaaab" =~ /
3443 \& (?:
3444 \& a # non\-zero
3445 \& | # or
3446 \& (?{print "hello"}) # print hello whenever this
3447 \& # branch is tried
3448 \& (?=(b)) # zero\-width assertion
3449 \& )* # any number of times
3450 \& /x;
3451 \& print $&;
3452 \& print $1;
3453 .Ve
3454 .PP
3455 prints
3456 .PP
3457 .Vb 3
3458 \& hello
3459 \& aaaaa
3460 \& b
3461 .Ve
3462 .PP
3463 Notice that "hello" is only printed once, as when Perl sees that the sixth
3464 iteration of the outermost \f(CW\*(C`(?:)*\*(C'\fR matches a zero\-length string, it stops
3465 the \f(CW"*"\fR.
3466 .PP
3467 The higher\-level loops preserve an additional state between iterations:
3468 whether the last match was zero\-length. To break the loop, the following
3469 match after a zero\-length match is prohibited to have a length of zero.
3470 This prohibition interacts with backtracking (see "Backtracking"),
3471 and so the \fIsecond best\fR match is chosen if the \fIbest\fR match is of
3472 zero length.
3473 .PP
3474 For example:
3475 .PP
3476 .Vb 2
3477 \& $_ = \*(Aqbar\*(Aq;
3478 \& s/\ew??/<$&>/g;
3479 .Ve
3480 .PP
3481 results in \f(CW\*(C`<><b><><a><><r><>\*(C'\fR. At each position of the string the best
3482 match given by non\-greedy \f(CW\*(C`??\*(C'\fR is the zero\-length match, and the \fIsecond
3483 best\fR match is what is matched by \f(CW\*(C`\ew\*(C'\fR. Thus zero\-length matches
3484 alternate with one\-character\-long matches.
3485 .PP
3486 Similarly, for repeated \f(CW\*(C`m/()/g\*(C'\fR the second\-best match is the match at the
3487 position one notch further in the string.
3488 .PP
3489 The additional state of being \fImatched with zero\-length\fR is associated with
3490 the matched string, and is reset by each assignment to \f(CWpos()\fR.
3491 Zero\-length matches at the end of the previous match are ignored
3492 during \f(CW\*(C`split\*(C'\fR.
3493 .SS "Combining RE Pieces"
3494 .IX Subsection "Combining RE Pieces"
3495 Each of the elementary pieces of regular expressions which were described
3496 before (such as \f(CW\*(C`ab\*(C'\fR or \f(CW\*(C`\eZ\*(C'\fR) could match at most one substring
3497 at the given position of the input string. However, in a typical regular
3498 expression these elementary pieces are combined into more complicated
3499 patterns using combining operators \f(CW\*(C`ST\*(C'\fR, \f(CW\*(C`S|T\*(C'\fR, \f(CW\*(C`S*\*(C'\fR \fIetc\fR.
3500 (in these examples \f(CW"S"\fR and \f(CW"T"\fR are regular subexpressions).
3501 .PP
3502 Such combinations can include alternatives, leading to a problem of choice:
3503 if we match a regular expression \f(CW\*(C`a|ab\*(C'\fR against \f(CW"abc"\fR, will it match
3504 substring \f(CW"a"\fR or \f(CW"ab"\fR? One way to describe which substring is
3505 actually matched is the concept of backtracking (see "Backtracking").
3506 However, this description is too low\-level and makes you think
3507 in terms of a particular implementation.
3508 .PP
3509 Another description starts with notions of "better"/"worse". All the
3510 substrings which may be matched by the given regular expression can be
3511 sorted from the "best" match to the "worst" match, and it is the "best"
3512 match which is chosen. This substitutes the question of "what is chosen?"
3513 by the question of "which matches are better, and which are worse?".
3514 .PP
3515 Again, for elementary pieces there is no such question, since at most
3516 one match at a given position is possible. This section describes the
3517 notion of better/worse for combining operators. In the description
3518 below \f(CW"S"\fR and \f(CW"T"\fR are regular subexpressions.
3519 .ie n .IP """ST""" 4
3520 .el .IP \f(CWST\fR 4
3521 .IX Item "ST"
3522 Consider two possible matches, \f(CW\*(C`AB\*(C'\fR and \f(CW\*(C`A\*(AqB\*(Aq\*(C'\fR, \f(CW"A"\fR and \f(CW\*(C`A\*(Aq\*(C'\fR are
3523 substrings which can be matched by \f(CW"S"\fR, \f(CW"B"\fR and \f(CW\*(C`B\*(Aq\*(C'\fR are substrings
3524 which can be matched by \f(CW"T"\fR.
3525 .Sp
3526 If \f(CW"A"\fR is a better match for \f(CW"S"\fR than \f(CW\*(C`A\*(Aq\*(C'\fR, \f(CW\*(C`AB\*(C'\fR is a better
3527 match than \f(CW\*(C`A\*(AqB\*(Aq\*(C'\fR.
3528 .Sp
3529 If \f(CW"A"\fR and \f(CW\*(C`A\*(Aq\*(C'\fR coincide: \f(CW\*(C`AB\*(C'\fR is a better match than \f(CW\*(C`AB\*(Aq\*(C'\fR if
3530 \&\f(CW"B"\fR is a better match for \f(CW"T"\fR than \f(CW\*(C`B\*(Aq\*(C'\fR.
3531 .ie n .IP """S|T""" 4
3532 .el .IP \f(CWS|T\fR 4
3533 .IX Item "S|T"
3534 When \f(CW"S"\fR can match, it is a better match than when only \f(CW"T"\fR can match.
3535 .Sp
3536 Ordering of two matches for \f(CW"S"\fR is the same as for \f(CW"S"\fR. Similar for
3537 two matches for \f(CW"T"\fR.
3538 .ie n .IP """S{REPEAT_COUNT}""" 4
3539 .el .IP \f(CWS{REPEAT_COUNT}\fR 4
3540 .IX Item "S{REPEAT_COUNT}"
3541 Matches as \f(CW\*(C`SSS...S\*(C'\fR (repeated as many times as necessary).
3542 .ie n .IP """S{min,max}""" 4
3543 .el .IP \f(CWS{min,max}\fR 4
3544 .IX Item "S{min,max}"
3545 Matches as \f(CW\*(C`S{max}|S{max\-1}|...|S{min+1}|S{min}\*(C'\fR.
3546 .ie n .IP """S{min,max}?""" 4
3547 .el .IP \f(CWS{min,max}?\fR 4
3548 .IX Item "S{min,max}?"
3549 Matches as \f(CW\*(C`S{min}|S{min+1}|...|S{max\-1}|S{max}\*(C'\fR.
3550 .ie n .IP """S?"", ""S*"", ""S+""" 4
3551 .el .IP "\f(CWS?\fR, \f(CWS*\fR, \f(CWS+\fR" 4
3552 .IX Item "S?, S*, S+"
3553 Same as \f(CW\*(C`S{0,1}\*(C'\fR, \f(CW\*(C`S{0,BIG_NUMBER}\*(C'\fR, \f(CW\*(C`S{1,BIG_NUMBER}\*(C'\fR respectively.
3554 .ie n .IP """S??"", ""S*?"", ""S+?""" 4
3555 .el .IP "\f(CWS??\fR, \f(CWS*?\fR, \f(CWS+?\fR" 4
3556 .IX Item "S??, S*?, S+?"
3557 Same as \f(CW\*(C`S{0,1}?\*(C'\fR, \f(CW\*(C`S{0,BIG_NUMBER}?\*(C'\fR, \f(CW\*(C`S{1,BIG_NUMBER}?\*(C'\fR respectively.
3558 .ie n .IP """(?>S)""" 4
3559 .el .IP \f(CW(?>S)\fR 4
3560 .IX Item "(?>S)"
3561 Matches the best match for \f(CW"S"\fR and only that.
3562 .ie n .IP """(?=S)"", ""(?<=S)""" 4
3563 .el .IP "\f(CW(?=S)\fR, \f(CW(?<=S)\fR" 4
3564 .IX Item "(?=S), (?<=S)"
3565 Only the best match for \f(CW"S"\fR is considered. (This is important only if
3566 \&\f(CW"S"\fR has capturing parentheses, and backreferences are used somewhere
3567 else in the whole regular expression.)
3568 .ie n .IP """(?!S)"", ""(?<!S)""" 4
3569 .el .IP "\f(CW(?!S)\fR, \f(CW(?<!S)\fR" 4
3570 .IX Item "(?!S), (?<!S)"
3571 For this grouping operator there is no need to describe the ordering, since
3572 only whether or not \f(CW"S"\fR can match is important.
3573 .ie n .IP """(??{ \fIEXPR\fR })"", ""(?\fIPARNO\fR)""" 4
3574 .el .IP "\f(CW(??{ \fR\f(CIEXPR\fR\f(CW })\fR, \f(CW(?\fR\f(CIPARNO\fR\f(CW)\fR" 4
3575 .IX Item "(??{ EXPR }), (?PARNO)"
3576 The ordering is the same as for the regular expression which is
3577 the result of \fIEXPR\fR, or the pattern contained by capture group \fIPARNO\fR.
3578 .ie n .IP """(?(\fIcondition\fR)\fIyes\-pattern\fR|\fIno\-pattern\fR)""" 4
3579 .el .IP \f(CW(?(\fR\f(CIcondition\fR\f(CW)\fR\f(CIyes\-pattern\fR\f(CW|\fR\f(CIno\-pattern\fR\f(CW)\fR 4
3580 .IX Item "(?(condition)yes-pattern|no-pattern)"
3581 Recall that which of \fIyes\-pattern\fR or \fIno\-pattern\fR actually matches is
3582 already determined. The ordering of the matches is the same as for the
3583 chosen subexpression.
3584 .PP
3585 The above recipes describe the ordering of matches \fIat a given position\fR.
3586 One more rule is needed to understand how a match is determined for the
3587 whole regular expression: a match at an earlier position is always better
3588 than a match at a later position.
3589 .SS "Creating Custom RE Engines"
3590 .IX Subsection "Creating Custom RE Engines"
3591 As of Perl 5.10.0, one can create custom regular expression engines. This
3592 is not for the faint of heart, as they have to plug in at the C level. See
3593 perlreapi for more details.
3594 .PP
3595 As an alternative, overloaded constants (see overload) provide a simple
3596 way to extend the functionality of the RE engine, by substituting one
3597 pattern for another.
3598 .PP
3599 Suppose that we want to enable a new RE escape\-sequence \f(CW\*(C`\eY|\*(C'\fR which
3600 matches at a boundary between whitespace characters and non\-whitespace
3601 characters. Note that \f(CW\*(C`(?=\eS)(?<!\eS)|(?!\eS)(?<=\eS)\*(C'\fR matches exactly
3602 at these positions, so we want to have each \f(CW\*(C`\eY|\*(C'\fR in the place of the
3603 more complicated version. We can create a module \f(CW\*(C`customre\*(C'\fR to do
3604 this:
3605 .PP
3606 .Vb 2
3607 \& package customre;
3608 \& use overload;
3609 \&
3610 \& sub import {
3611 \& shift;
3612 \& die "No argument to customre::import allowed" if @_;
3613 \& overload::constant \*(Aqqr\*(Aq => \e&convert;
3614 \& }
3615 \&
3616 \& sub invalid { die "/$_[0]/: invalid escape \*(Aq\e\e$_[1]\*(Aq"}
3617 \&
3618 \& # We must also take care of not escaping the legitimate \e\eY|
3619 \& # sequence, hence the presence of \*(Aq\e\e\*(Aq in the conversion rules.
3620 \& my %rules = ( \*(Aq\e\e\*(Aq => \*(Aq\e\e\e\e\*(Aq,
3621 \& \*(AqY|\*(Aq => qr/(?=\eS)(?<!\eS)|(?!\eS)(?<=\eS)/ );
3622 \& sub convert {
3623 \& my $re = shift;
3624 \& $re =~ s{
3625 \& \e\e ( \e\e | Y . )
3626 \& }
3627 \& { $rules{$1} or invalid($re,$1) }sgex;
3628 \& return $re;
3629 \& }
3630 .Ve
3631 .PP
3632 Now \f(CW\*(C`use customre\*(C'\fR enables the new escape in constant regular
3633 expressions, \fIi.e.\fR, those without any runtime variable interpolations.
3634 As documented in overload, this conversion will work only over
3635 literal parts of regular expressions. For \f(CW\*(C`\eY|$re\eY|\*(C'\fR the variable
3636 part of this regular expression needs to be converted explicitly
3637 (but only if the special meaning of \f(CW\*(C`\eY|\*(C'\fR should be enabled inside \f(CW$re\fR):
3638 .PP
3639 .Vb 5
3640 \& use customre;
3641 \& $re = <>;
3642 \& chomp $re;
3643 \& $re = customre::convert $re;
3644 \& /\eY|$re\eY|/;
3645 .Ve
3646 .SS "Embedded Code Execution Frequency"
3647 .IX Subsection "Embedded Code Execution Frequency"
3648 The exact rules for how often \f(CW\*(C`(?{})\*(C'\fR and \f(CW\*(C`(??{})\*(C'\fR are executed in a pattern
3649 are unspecified, and this is even more true of \f(CW\*(C`(*{})\*(C'\fR.
3650 In the case of a successful match you can assume that they DWIM and
3651 will be executed in left to right order the appropriate number of times in the
3652 accepting path of the pattern as would any other meta\-pattern. How non\-
3653 accepting pathways and match failures affect the number of times a pattern is
3654 executed is specifically unspecified and may vary depending on what
3655 optimizations can be applied to the pattern and is likely to change from
3656 version to version.
3657 .PP
3658 For instance in
3659 .PP
3660 .Vb 1
3661 \& "aaabcdeeeee"=~/a(?{print "a"})b(?{print "b"})cde/;
3662 .Ve
3663 .PP
3664 the exact number of times "a" or "b" are printed out is unspecified for
3665 failure, but you may assume they will be printed at least once during
3666 a successful match, additionally you may assume that if "b" is printed,
3667 it will be preceded by at least one "a".
3668 .PP
3669 In the case of branching constructs like the following:
3670 .PP
3671 .Vb 1
3672 \& /a(b|(?{ print "a" }))c(?{ print "c" })/;
3673 .Ve
3674 .PP
3675 you can assume that the input "ac" will output "ac", and that "abc"
3676 will output only "c".
3677 .PP
3678 When embedded code is quantified, successful matches will call the
3679 code once for each matched iteration of the quantifier. For
3680 example:
3681 .PP
3682 .Vb 1
3683 \& "good" =~ /g(?:o(?{print "o"}))*d/;
3684 .Ve
3685 .PP
3686 will output "o" twice.
3687 .PP
3688 For historical and consistency reasons the use of normal code blocks
3689 anywhere in a pattern will disable certain optimisations. As of 5.37.7
3690 you can use an "optimistic" codeblock, \f(CW\*(C`(*{ ... })\*(C'\fR as a replacement
3691 for \f(CW\*(C`(?{ ... })\*(C'\fR, if you do *not* wish to disable these optimisations.
3692 This may result in the code block being called less often than it might
3693 have been had they not been optimistic.
3694 .SS "PCRE/Python Support"
3695 .IX Subsection "PCRE/Python Support"
3696 As of Perl 5.10.0, Perl supports several Python/PCRE\-specific extensions
3697 to the regex syntax. While Perl programmers are encouraged to use the
3698 Perl\-specific syntax, the following are also accepted:
3699 .ie n .IP """(?P<\fINAME\fR>\fIpattern\fR)""" 4
3700 .el .IP \f(CW(?P<\fR\f(CINAME\fR\f(CW>\fR\f(CIpattern\fR\f(CW)\fR 4
3701 .IX Item "(?P<NAME>pattern)"
3702 Define a named capture group. Equivalent to \f(CW\*(C`(?<\fR\f(CINAME\fR\f(CW>\fR\f(CIpattern\fR\f(CW)\*(C'\fR.
3703 .ie n .IP """(?P=\fINAME\fR)""" 4
3704 .el .IP \f(CW(?P=\fR\f(CINAME\fR\f(CW)\fR 4
3705 .IX Item "(?P=NAME)"
3706 Backreference to a named capture group. Equivalent to \f(CW\*(C`\eg{\fR\f(CINAME\fR\f(CW}\*(C'\fR.
3707 .ie n .IP """(?P>\fINAME\fR)""" 4
3708 .el .IP \f(CW(?P>\fR\f(CINAME\fR\f(CW)\fR 4
3709 .IX Item "(?P>NAME)"
3710 Subroutine call to a named capture group. Equivalent to \f(CW\*(C`(?&\fR\f(CINAME\fR\f(CW)\*(C'\fR.
3711 .SS "Quoting metacharacters"
3712 .IX Subsection "Quoting metacharacters"
3713 This section has been replaced by "Quoting (escaping) metacharacters".
3714 .SH BUGS
3715 .IX Header "BUGS"
3716 There are a number of issues with regard to case\-insensitive matching
3717 in Unicode rules. See \f(CW"i"\fR under "Modifiers" above.
3718 .PP
3719 This document varies from difficult to understand to completely
3720 and utterly opaque. The wandering prose riddled with jargon is
3721 hard to fathom in several places.
3722 .PP
3723 This document needs a rewrite that separates the tutorial content
3724 from the reference content.
3725 .SH "SEE ALSO"
3726 .IX Header "SEE ALSO"
3727 The syntax of patterns used in Perl pattern matching evolved from those
3728 supplied in the Bell Labs Research Unix 8th Edition (Version 8) regex
3729 routines. (The code is actually derived (distantly) from Henry
3730 Spencer\*(Aqs freely redistributable reimplementation of those V8 routines.)
3731 .PP
3732 perlrequick.
3733 .PP
3734 perlretut.
3735 .PP
3736 "Regexp Quote\-Like Operators" in perlop.
3737 .PP
3738 "Gory details of parsing quoted constructs" in perlop.
3739 .PP
3740 perlfaq6.
3741 .PP
3742 "pos" in perlfunc.
3743 .PP
3744 perllocale.
3745 .PP
3746 perlebcdic.
3747 .PP
3748 \&\fIMastering Regular Expressions\fR by Jeffrey Friedl, published
3749 by O\*(AqReilly and Associates.