Debian Codegraph @

upstream/fedora-44/man1/perlretut.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 "PERLRETUT 1"
61 .TH PERLRETUT 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 perlretut \- Perl regular expressions tutorial
68 .SH DESCRIPTION
69 .IX Header "DESCRIPTION"
70 This page provides a basic tutorial on understanding, creating and
71 using regular expressions in Perl. It serves as a complement to the
72 reference page on regular expressions perlre. Regular expressions
73 are an integral part of the \f(CW\*(C`m//\*(C'\fR, \f(CW\*(C`s///\*(C'\fR, \f(CW\*(C`qr//\*(C'\fR and \f(CW\*(C`split\*(C'\fR
74 operators and so this tutorial also overlaps with
75 "Regexp Quote\-Like Operators" in perlop and "split" in perlfunc.
76 .PP
77 Perl is widely renowned for excellence in text processing, and regular
78 expressions are one of the big factors behind this fame. Perl regular
79 expressions display an efficiency and flexibility unknown in most
80 other computer languages. Mastering even the basics of regular
81 expressions will allow you to manipulate text with surprising ease.
82 .PP
83 What is a regular expression? At its most basic, a regular expression
84 is a template that is used to determine if a string has certain
85 characteristics. The string is most often some text, such as a line,
86 sentence, web page, or even a whole book, but it doesn\*(Aqt have to be. It
87 could be binary data, for example. Biologists often use Perl to look
88 for patterns in long DNA sequences.
89 .PP
90 Suppose we want to determine if the text in variable, \f(CW$var\fR contains
91 the sequence of characters \f(CW\*(C`m\ u\ s\ h\ r\ o\ o\ m\*(C'\fR
92 (blanks added for legibility). We can write in Perl
93 .PP
94 .Vb 1
95 \& $var =~ m/mushroom/
96 .Ve
97 .PP
98 The value of this expression will be TRUE if \f(CW$var\fR contains that
99 sequence of characters anywhere within it, and FALSE otherwise. The
100 portion enclosed in \f(CW\*(Aq/\*(Aq\fR characters denotes the characteristic we
101 are looking for.
102 We use the term \fIpattern\fR for it. The process of looking to see if the
103 pattern occurs in the string is called \fImatching\fR, and the \f(CW"=~"\fR
104 operator along with the \f(CW\*(C`m//\*(C'\fR tell Perl to try to match the pattern
105 against the string. Note that the pattern is also a string, but a very
106 special kind of one, as we will see. Patterns are in common use these
107 days;
108 examples are the patterns typed into a search engine to find web pages
109 and the patterns used to list files in a directory, \fIe.g.\fR, "\f(CW\*(C`ls *.txt\*(C'\fR"
110 or "\f(CW\*(C`dir *.*\*(C'\fR". In Perl, the patterns described by regular expressions
111 are used not only to search strings, but to also extract desired parts
112 of strings, and to do search and replace operations.
113 .PP
114 Regular expressions have the undeserved reputation of being abstract
115 and difficult to understand. This really stems simply because the
116 notation used to express them tends to be terse and dense, and not
117 because of inherent complexity. We recommend using the \f(CW\*(C`/x\*(C'\fR regular
118 expression modifier (described below) along with plenty of white space
119 to make them less dense, and easier to read. Regular expressions are
120 constructed using
121 simple concepts like conditionals and loops and are no more difficult
122 to understand than the corresponding \f(CW\*(C`if\*(C'\fR conditionals and \f(CW\*(C`while\*(C'\fR
123 loops in the Perl language itself.
124 .PP
125 This tutorial flattens the learning curve by discussing regular
126 expression concepts, along with their notation, one at a time and with
127 many examples. The first part of the tutorial will progress from the
128 simplest word searches to the basic regular expression concepts. If
129 you master the first part, you will have all the tools needed to solve
130 about 98% of your needs. The second part of the tutorial is for those
131 comfortable with the basics, and hungry for more power tools. It
132 discusses the more advanced regular expression operators and
133 introduces the latest cutting\-edge innovations.
134 .PP
135 A note: to save time, "regular expression" is often abbreviated as
136 regexp or regex. Regexp is a more natural abbreviation than regex, but
137 is harder to pronounce. The Perl pod documentation is evenly split on
138 regexp vs regex; in Perl, there is more than one way to abbreviate it.
139 We\*(Aqll use regexp in this tutorial.
140 .PP
141 New in v5.22, \f(CW\*(C`use re \*(Aqstrict\*(Aq\*(C'\fR applies stricter
142 rules than otherwise when compiling regular expression patterns. It can
143 find things that, while legal, may not be what you intended.
144 .SH "Part 1: The basics"
145 .IX Header "Part 1: The basics"
146 .SS "Simple word matching"
147 .IX Subsection "Simple word matching"
148 The simplest regexp is simply a word, or more generally, a string of
149 characters. A regexp consisting of just a word matches any string that
150 contains that word:
151 .PP
152 .Vb 1
153 \& "Hello World" =~ /World/; # matches
154 .Ve
155 .PP
156 What is this Perl statement all about? \f(CW"Hello World"\fR is a simple
157 double\-quoted string. \f(CW\*(C`World\*(C'\fR is the regular expression and the
158 \&\f(CW\*(C`//\*(C'\fR enclosing \f(CW\*(C`/World/\*(C'\fR tells Perl to search a string for a match.
159 The operator \f(CW\*(C`=~\*(C'\fR associates the string with the regexp match and
160 produces a true value if the regexp matched, or false if the regexp
161 did not match. In our case, \f(CW\*(C`World\*(C'\fR matches the second word in
162 \&\f(CW"Hello World"\fR, so the expression is true. Expressions like this
163 are useful in conditionals:
164 .PP
165 .Vb 6
166 \& if ("Hello World" =~ /World/) {
167 \& print "It matches\en";
168 \& }
169 \& else {
170 \& print "It doesn\*(Aqt match\en";
171 \& }
172 .Ve
173 .PP
174 There are useful variations on this theme. The sense of the match can
175 be reversed by using the \f(CW\*(C`!~\*(C'\fR operator:
176 .PP
177 .Vb 6
178 \& if ("Hello World" !~ /World/) {
179 \& print "It doesn\*(Aqt match\en";
180 \& }
181 \& else {
182 \& print "It matches\en";
183 \& }
184 .Ve
185 .PP
186 The literal string in the regexp can be replaced by a variable:
187 .PP
188 .Vb 7
189 \& my $greeting = "World";
190 \& if ("Hello World" =~ /$greeting/) {
191 \& print "It matches\en";
192 \& }
193 \& else {
194 \& print "It doesn\*(Aqt match\en";
195 \& }
196 .Ve
197 .PP
198 If you\*(Aqre matching against the special default variable \f(CW$_\fR, the
199 \&\f(CW\*(C`$_ =~\*(C'\fR part can be omitted:
200 .PP
201 .Vb 7
202 \& $_ = "Hello World";
203 \& if (/World/) {
204 \& print "It matches\en";
205 \& }
206 \& else {
207 \& print "It doesn\*(Aqt match\en";
208 \& }
209 .Ve
210 .PP
211 And finally, the \f(CW\*(C`//\*(C'\fR default delimiters for a match can be changed
212 to arbitrary delimiters by putting an \f(CW\*(Aqm\*(Aq\fR out front:
213 .PP
214 .Vb 4
215 \& "Hello World" =~ m!World!; # matches, delimited by \*(Aq!\*(Aq
216 \& "Hello World" =~ m{World}; # matches, note the paired \*(Aq{}\*(Aq
217 \& "/usr/bin/perl" =~ m"/perl"; # matches after \*(Aq/usr/bin\*(Aq,
218 \& # \*(Aq/\*(Aq becomes an ordinary char
219 .Ve
220 .PP
221 \&\f(CW\*(C`/World/\*(C'\fR, \f(CW\*(C`m!World!\*(C'\fR, and \f(CW\*(C`m{World}\*(C'\fR all represent the
222 same thing. When, \fIe.g.\fR, the quote (\f(CW\*(Aq"\*(Aq\fR) is used as a delimiter, the forward
223 slash \f(CW\*(Aq/\*(Aq\fR becomes an ordinary character and can be used in this regexp
224 without trouble.
225 .PP
226 Let\*(Aqs consider how different regexps would match \f(CW"Hello World"\fR:
227 .PP
228 .Vb 4
229 \& "Hello World" =~ /world/; # doesn\*(Aqt match
230 \& "Hello World" =~ /o W/; # matches
231 \& "Hello World" =~ /oW/; # doesn\*(Aqt match
232 \& "Hello World" =~ /World /; # doesn\*(Aqt match
233 .Ve
234 .PP
235 The first regexp \f(CW\*(C`world\*(C'\fR doesn\*(Aqt match because regexps are by default
236 case\-sensitive. The second regexp matches because the substring
237 \&\f(CW\*(Aqo\ W\*(Aq\fR occurs in the string \f(CW"Hello\ World"\fR. The space
238 character \f(CW\*(Aq \*(Aq\fR is treated like any other character in a regexp and is
239 needed to match in this case. The lack of a space character is the
240 reason the third regexp \f(CW\*(AqoW\*(Aq\fR doesn\*(Aqt match. The fourth regexp
241 "\f(CW\*(C`World \*(C'\fR" doesn\*(Aqt match because there is a space at the end of the
242 regexp, but not at the end of the string. The lesson here is that
243 regexps must match a part of the string \fIexactly\fR in order for the
244 statement to be true.
245 .PP
246 If a regexp matches in more than one place in the string, Perl will
247 always match at the earliest possible point in the string:
248 .PP
249 .Vb 2
250 \& "Hello World" =~ /o/; # matches \*(Aqo\*(Aq in \*(AqHello\*(Aq
251 \& "That hat is red" =~ /hat/; # matches \*(Aqhat\*(Aq in \*(AqThat\*(Aq
252 .Ve
253 .PP
254 With respect to character matching, there are a few more points you
255 need to know about. First of all, not all characters can be used
256 "as\-is" in a match. Some characters, called \fImetacharacters\fR, are
257 generally reserved for use in regexp notation. The metacharacters are
258 .PP
259 .Vb 1
260 \& {}[]()^$.|*+?\-#\e
261 .Ve
262 .PP
263 This list is not as definitive as it may appear (or be claimed to be in
264 other documentation). For example, \f(CW"#"\fR is a metacharacter only when
265 the \f(CW\*(C`/x\*(C'\fR pattern modifier (described below) is used, and both \f(CW"}"\fR
266 and \f(CW"]"\fR are metacharacters only when paired with opening \f(CW"{"\fR or
267 \&\f(CW"["\fR respectively; other gotchas apply.
268 .PP
269 The significance of each of these will be explained
270 in the rest of the tutorial, but for now, it is important only to know
271 that a metacharacter can be matched as\-is by putting a backslash before
272 it. This is called "escaping" or "quoting" it. Some examples:
273 .PP
274 .Vb 5
275 \& "2+2=4" =~ /2+2/; # doesn\*(Aqt match, + is a metacharacter
276 \& "2+2=4" =~ /2\e+2/; # matches, \e+ is treated like an ordinary +
277 \& "The interval is [0,1)." =~ /[0,1)./ # is a syntax error!
278 \& "The interval is [0,1)." =~ /\e[0,1\e)\e./ # matches
279 \& "#!/usr/bin/perl" =~ /#!\e/usr\e/bin\e/perl/; # matches
280 .Ve
281 .PP
282 In the last regexp, the forward slash \f(CW\*(Aq/\*(Aq\fR is also backslashed,
283 because it is used to delimit the regexp. This can lead to LTS
284 (leaning toothpick syndrome), however, and it is often more readable
285 to change delimiters.
286 .PP
287 .Vb 1
288 \& "#!/usr/bin/perl" =~ m!#\e!/usr/bin/perl!; # easier to read
289 .Ve
290 .PP
291 The backslash character \f(CW\*(Aq\e\*(Aq\fR is a metacharacter itself and needs to
292 be backslashed:
293 .PP
294 .Vb 1
295 \& \*(AqC:\eWIN32\*(Aq =~ /C:\e\eWIN/; # matches
296 .Ve
297 .PP
298 In situations where it doesn\*(Aqt make sense for a particular metacharacter
299 to mean what it normally does, it automatically loses its
300 metacharacter\-ness and becomes an ordinary character that is to be
301 matched literally. For example, the \f(CW\*(Aq}\*(Aq\fR is a metacharacter only when
302 it is the mate of a \f(CW\*(Aq{\*(Aq\fR metacharacter. Otherwise it is treated as a
303 literal RIGHT CURLY BRACKET. This may lead to unexpected results.
304 \&\f(CW\*(C`use re \*(Aqstrict\*(Aq\*(C'\fR can catch some of these.
305 .PP
306 In addition to the metacharacters, there are some ASCII characters
307 which don\*(Aqt have printable character equivalents and are instead
308 represented by \fIescape sequences\fR. Common examples are \f(CW\*(C`\et\*(C'\fR for a
309 tab, \f(CW\*(C`\en\*(C'\fR for a newline, \f(CW\*(C`\er\*(C'\fR for a carriage return and \f(CW\*(C`\ea\*(C'\fR for a
310 bell (or alert). If your string is better thought of as a sequence of arbitrary
311 bytes, the octal escape sequence, \fIe.g.\fR, \f(CW\*(C`\e033\*(C'\fR, or hexadecimal escape
312 sequence, \fIe.g.\fR, \f(CW\*(C`\ex1B\*(C'\fR may be a more natural representation for your
313 bytes. Here are some examples of escapes:
314 .PP
315 .Vb 5
316 \& "1000\et2000" =~ m(0\et2) # matches
317 \& "1000\en2000" =~ /0\en20/ # matches
318 \& "1000\et2000" =~ /\e000\et2/ # doesn\*(Aqt match, "0" ne "\e000"
319 \& "cat" =~ /\eo{143}\ex61\ex74/ # matches in ASCII, but a weird way
320 \& # to spell cat
321 .Ve
322 .PP
323 If you\*(Aqve been around Perl a while, all this talk of escape sequences
324 may seem familiar. Similar escape sequences are used in double\-quoted
325 strings and in fact the regexps in Perl are mostly treated as
326 double\-quoted strings. This means that variables can be used in
327 regexps as well. Just like double\-quoted strings, the values of the
328 variables in the regexp will be substituted in before the regexp is
329 evaluated for matching purposes. So we have:
330 .PP
331 .Vb 4
332 \& $foo = \*(Aqhouse\*(Aq;
333 \& \*(Aqhousecat\*(Aq =~ /$foo/; # matches
334 \& \*(Aqcathouse\*(Aq =~ /cat$foo/; # matches
335 \& \*(Aqhousecat\*(Aq =~ /${foo}cat/; # matches
336 .Ve
337 .PP
338 So far, so good. With the knowledge above you can already perform
339 searches with just about any literal string regexp you can dream up.
340 Here is a \fIvery simple\fR emulation of the Unix grep program:
341 .PP
342 .Vb 7
343 \& % cat > simple_grep
344 \& #!/usr/bin/perl
345 \& $regexp = shift;
346 \& while (<>) {
347 \& print if /$regexp/;
348 \& }
349 \& ^D
350 \&
351 \& % chmod +x simple_grep
352 \&
353 \& % simple_grep abba /usr/dict/words
354 \& Babbage
355 \& cabbage
356 \& cabbages
357 \& sabbath
358 \& Sabbathize
359 \& Sabbathizes
360 \& sabbatical
361 \& scabbard
362 \& scabbards
363 .Ve
364 .PP
365 This program is easy to understand. \f(CW\*(C`#!/usr/bin/perl\*(C'\fR is the standard
366 way to invoke a perl program from the shell.
367 \&\f(CW\*(C`$regexp\ =\ shift;\*(C'\fR saves the first command line argument as the
368 regexp to be used, leaving the rest of the command line arguments to
369 be treated as files. \f(CW\*(C`while\ (<>)\*(C'\fR loops over all the lines in
370 all the files. For each line, \f(CW\*(C`print\ if\ /$regexp/;\*(C'\fR prints the
371 line if the regexp matches the line. In this line, both \f(CW\*(C`print\*(C'\fR and
372 \&\f(CW\*(C`/$regexp/\*(C'\fR use the default variable \f(CW$_\fR implicitly.
373 .PP
374 With all of the regexps above, if the regexp matched anywhere in the
375 string, it was considered a match. Sometimes, however, we\*(Aqd like to
376 specify \fIwhere\fR in the string the regexp should try to match. To do
377 this, we would use the \fIanchor\fR metacharacters \f(CW\*(Aq^\*(Aq\fR and \f(CW\*(Aq$\*(Aq\fR. The
378 anchor \f(CW\*(Aq^\*(Aq\fR means match at the beginning of the string and the anchor
379 \&\f(CW\*(Aq$\*(Aq\fR means match at the end of the string, or before a newline at the
380 end of the string. Here is how they are used:
381 .PP
382 .Vb 4
383 \& "housekeeper" =~ /keeper/; # matches
384 \& "housekeeper" =~ /^keeper/; # doesn\*(Aqt match
385 \& "housekeeper" =~ /keeper$/; # matches
386 \& "housekeeper\en" =~ /keeper$/; # matches
387 .Ve
388 .PP
389 The second regexp doesn\*(Aqt match because \f(CW\*(Aq^\*(Aq\fR constrains \f(CW\*(C`keeper\*(C'\fR to
390 match only at the beginning of the string, but \f(CW"housekeeper"\fR has
391 keeper starting in the middle. The third regexp does match, since the
392 \&\f(CW\*(Aq$\*(Aq\fR constrains \f(CW\*(C`keeper\*(C'\fR to match only at the end of the string.
393 .PP
394 When both \f(CW\*(Aq^\*(Aq\fR and \f(CW\*(Aq$\*(Aq\fR are used at the same time, the regexp has to
395 match both the beginning and the end of the string, \fIi.e.\fR, the regexp
396 matches the whole string. Consider
397 .PP
398 .Vb 3
399 \& "keeper" =~ /^keep$/; # doesn\*(Aqt match
400 \& "keeper" =~ /^keeper$/; # matches
401 \& "" =~ /^$/; # ^$ matches an empty string
402 .Ve
403 .PP
404 The first regexp doesn\*(Aqt match because the string has more to it than
405 \&\f(CW\*(C`keep\*(C'\fR. Since the second regexp is exactly the string, it
406 matches. Using both \f(CW\*(Aq^\*(Aq\fR and \f(CW\*(Aq$\*(Aq\fR in a regexp forces the complete
407 string to match, so it gives you complete control over which strings
408 match and which don\*(Aqt. Suppose you are looking for a fellow named
409 bert, off in a string by himself:
410 .PP
411 .Vb 1
412 \& "dogbert" =~ /bert/; # matches, but not what you want
413 \&
414 \& "dilbert" =~ /^bert/; # doesn\*(Aqt match, but ..
415 \& "bertram" =~ /^bert/; # matches, so still not good enough
416 \&
417 \& "bertram" =~ /^bert$/; # doesn\*(Aqt match, good
418 \& "dilbert" =~ /^bert$/; # doesn\*(Aqt match, good
419 \& "bert" =~ /^bert$/; # matches, perfect
420 .Ve
421 .PP
422 Of course, in the case of a literal string, one could just as easily
423 use the string comparison \f(CW\*(C`$string\ eq\ \*(Aqbert\*(Aq\*(C'\fR and it would be
424 more efficient. The \f(CW\*(C`^...$\*(C'\fR regexp really becomes useful when we
425 add in the more powerful regexp tools below.
426 .SS "Using character classes"
427 .IX Subsection "Using character classes"
428 Although one can already do quite a lot with the literal string
429 regexps above, we\*(Aqve only scratched the surface of regular expression
430 technology. In this and subsequent sections we will introduce regexp
431 concepts (and associated metacharacter notations) that will allow a
432 regexp to represent not just a single character sequence, but a \fIwhole
433 class\fR of them.
434 .PP
435 One such concept is that of a \fIcharacter class\fR. A character class
436 allows a set of possible characters, rather than just a single
437 character, to match at a particular point in a regexp. You can define
438 your own custom character classes. These
439 are denoted by brackets \f(CW\*(C`[...]\*(C'\fR, with the set of characters
440 to be possibly matched inside. Here are some examples:
441 .PP
442 .Vb 4
443 \& /cat/; # matches \*(Aqcat\*(Aq
444 \& /[bcr]at/; # matches \*(Aqbat, \*(Aqcat\*(Aq, or \*(Aqrat\*(Aq
445 \& /item[0123456789]/; # matches \*(Aqitem0\*(Aq or ... or \*(Aqitem9\*(Aq
446 \& "abc" =~ /[cab]/; # matches \*(Aqa\*(Aq
447 .Ve
448 .PP
449 In the last statement, even though \f(CW\*(Aqc\*(Aq\fR is the first character in
450 the class, \f(CW\*(Aqa\*(Aq\fR matches because the first character position in the
451 string is the earliest point at which the regexp can match.
452 .PP
453 .Vb 2
454 \& /[yY][eE][sS]/; # match \*(Aqyes\*(Aq in a case\-insensitive way
455 \& # \*(Aqyes\*(Aq, \*(AqYes\*(Aq, \*(AqYES\*(Aq, etc.
456 .Ve
457 .PP
458 This regexp displays a common task: perform a case\-insensitive
459 match. Perl provides a way of avoiding all those brackets by simply
460 appending an \f(CW\*(Aqi\*(Aq\fR to the end of the match. Then \f(CW\*(C`/[yY][eE][sS]/;\*(C'\fR
461 can be rewritten as \f(CW\*(C`/yes/i;\*(C'\fR. The \f(CW\*(Aqi\*(Aq\fR stands for
462 case\-insensitive and is an example of a \fImodifier\fR of the matching
463 operation. We will meet other modifiers later in the tutorial.
464 .PP
465 We saw in the section above that there were ordinary characters, which
466 represented themselves, and special characters, which needed a
467 backslash \f(CW\*(Aq\e\*(Aq\fR to represent themselves. The same is true in a
468 character class, but the sets of ordinary and special characters
469 inside a character class are different than those outside a character
470 class. The special characters for a character class are \f(CW\*(C`\-]\e^$\*(C'\fR (and
471 the pattern delimiter, whatever it is).
472 \&\f(CW\*(Aq]\*(Aq\fR is special because it denotes the end of a character class. \f(CW\*(Aq$\*(Aq\fR is
473 special because it denotes a scalar variable. \f(CW\*(Aq\e\*(Aq\fR is special because
474 it is used in escape sequences, just like above. Here is how the
475 special characters \f(CW\*(C`]$\e\*(C'\fR are handled:
476 .PP
477 .Vb 5
478 \& /[\e]c]def/; # matches \*(Aq]def\*(Aq or \*(Aqcdef\*(Aq
479 \& $x = \*(Aqbcr\*(Aq;
480 \& /[$x]at/; # matches \*(Aqbat\*(Aq, \*(Aqcat\*(Aq, or \*(Aqrat\*(Aq
481 \& /[\e$x]at/; # matches \*(Aq$at\*(Aq or \*(Aqxat\*(Aq
482 \& /[\e\e$x]at/; # matches \*(Aq\eat\*(Aq, \*(Aqbat, \*(Aqcat\*(Aq, or \*(Aqrat\*(Aq
483 .Ve
484 .PP
485 The last two are a little tricky. In \f(CW\*(C`[\e$x]\*(C'\fR, the backslash protects
486 the dollar sign, so the character class has two members \f(CW\*(Aq$\*(Aq\fR and \f(CW\*(Aqx\*(Aq\fR.
487 In \f(CW\*(C`[\e\e$x]\*(C'\fR, the backslash is protected, so \f(CW$x\fR is treated as a
488 variable and substituted in double quote fashion.
489 .PP
490 The special character \f(CW\*(Aq\-\*(Aq\fR acts as a range operator within character
491 classes, so that a contiguous set of characters can be written as a
492 range. With ranges, the unwieldy \f(CW\*(C`[0123456789]\*(C'\fR and \f(CW\*(C`[abc...xyz]\*(C'\fR
493 become the svelte \f(CW\*(C`[0\-9]\*(C'\fR and \f(CW\*(C`[a\-z]\*(C'\fR. Some examples are
494 .PP
495 .Vb 6
496 \& /item[0\-9]/; # matches \*(Aqitem0\*(Aq or ... or \*(Aqitem9\*(Aq
497 \& /[0\-9bx\-z]aa/; # matches \*(Aq0aa\*(Aq, ..., \*(Aq9aa\*(Aq,
498 \& # \*(Aqbaa\*(Aq, \*(Aqxaa\*(Aq, \*(Aqyaa\*(Aq, or \*(Aqzaa\*(Aq
499 \& /[0\-9a\-fA\-F]/; # matches a hexadecimal digit
500 \& /[0\-9a\-zA\-Z_]/; # matches a "word" character,
501 \& # like those in a Perl variable name
502 .Ve
503 .PP
504 If \f(CW\*(Aq\-\*(Aq\fR is the first or last character in a character class, it is
505 treated as an ordinary character; \f(CW\*(C`[\-ab]\*(C'\fR, \f(CW\*(C`[ab\-]\*(C'\fR and \f(CW\*(C`[a\e\-b]\*(C'\fR are
506 all equivalent.
507 .PP
508 The special character \f(CW\*(Aq^\*(Aq\fR in the first position of a character class
509 denotes a \fInegated character class\fR, which matches any character but
510 those in the brackets. Both \f(CW\*(C`[...]\*(C'\fR and \f(CW\*(C`[^...]\*(C'\fR must match a
511 character, or the match fails. Then
512 .PP
513 .Vb 4
514 \& /[^a]at/; # doesn\*(Aqt match \*(Aqaat\*(Aq or \*(Aqat\*(Aq, but matches
515 \& # all other \*(Aqbat\*(Aq, \*(Aqcat, \*(Aq0at\*(Aq, \*(Aq%at\*(Aq, etc.
516 \& /[^0\-9]/; # matches a non\-numeric character
517 \& /[a^]at/; # matches \*(Aqaat\*(Aq or \*(Aq^at\*(Aq; here \*(Aq^\*(Aq is ordinary
518 .Ve
519 .PP
520 Now, even \f(CW\*(C`[0\-9]\*(C'\fR can be a bother to write multiple times, so in the
521 interest of saving keystrokes and making regexps more readable, Perl
522 has several abbreviations for common character classes, as shown below.
523 Since the introduction of Unicode, unless the \f(CW\*(C`/a\*(C'\fR modifier is in
524 effect, these character classes match more than just a few characters in
525 the ASCII range.
526 .IP \(bu 4
527 \&\f(CW\*(C`\ed\*(C'\fR matches a digit, not just \f(CW\*(C`[0\-9]\*(C'\fR but also digits from non\-roman scripts
528 .IP \(bu 4
529 \&\f(CW\*(C`\es\*(C'\fR matches a whitespace character, the set \f(CW\*(C`[\e \et\er\en\ef]\*(C'\fR and others
530 .IP \(bu 4
531 \&\f(CW\*(C`\ew\*(C'\fR matches a word character (alphanumeric or \f(CW\*(Aq_\*(Aq\fR), not just \f(CW\*(C`[0\-9a\-zA\-Z_]\*(C'\fR
532 but also digits and characters from non\-roman scripts
533 .IP \(bu 4
534 \&\f(CW\*(C`\eD\*(C'\fR is a negated \f(CW\*(C`\ed\*(C'\fR; it represents any other character than a digit, or \f(CW\*(C`[^\ed]\*(C'\fR
535 .IP \(bu 4
536 \&\f(CW\*(C`\eS\*(C'\fR is a negated \f(CW\*(C`\es\*(C'\fR; it represents any non\-whitespace character \f(CW\*(C`[^\es]\*(C'\fR
537 .IP \(bu 4
538 \&\f(CW\*(C`\eW\*(C'\fR is a negated \f(CW\*(C`\ew\*(C'\fR; it represents any non\-word character \f(CW\*(C`[^\ew]\*(C'\fR
539 .IP \(bu 4
540 The period \f(CW\*(Aq.\*(Aq\fR matches any character but \f(CW"\en"\fR (unless the modifier \f(CW\*(C`/s\*(C'\fR is
541 in effect, as explained below).
542 .IP \(bu 4
543 \&\f(CW\*(C`\eN\*(C'\fR, like the period, matches any character but \f(CW"\en"\fR, but it does so
544 regardless of whether the modifier \f(CW\*(C`/s\*(C'\fR is in effect.
545 .PP
546 The \f(CW\*(C`/a\*(C'\fR modifier, available starting in Perl 5.14, is used to
547 restrict the matches of \f(CW\*(C`\ed\*(C'\fR, \f(CW\*(C`\es\*(C'\fR, and \f(CW\*(C`\ew\*(C'\fR to just those in the ASCII range.
548 It is useful to keep your program from being needlessly exposed to full
549 Unicode (and its accompanying security considerations) when all you want
550 is to process English\-like text. (The "a" may be doubled, \f(CW\*(C`/aa\*(C'\fR, to
551 provide even more restrictions, preventing case\-insensitive matching of
552 ASCII with non\-ASCII characters; otherwise a Unicode "Kelvin Sign"
553 would caselessly match a "k" or "K".)
554 .PP
555 The \f(CW\*(C`\ed\es\ew\eD\eS\eW\*(C'\fR abbreviations can be used both inside and outside
556 of bracketed character classes. Here are some in use:
557 .PP
558 .Vb 7
559 \& /\ed\ed:\ed\ed:\ed\ed/; # matches a hh:mm:ss time format
560 \& /[\ed\es]/; # matches any digit or whitespace character
561 \& /\ew\eW\ew/; # matches a word char, followed by a
562 \& # non\-word char, followed by a word char
563 \& /..rt/; # matches any two chars, followed by \*(Aqrt\*(Aq
564 \& /end\e./; # matches \*(Aqend.\*(Aq
565 \& /end[.]/; # same thing, matches \*(Aqend.\*(Aq
566 .Ve
567 .PP
568 Because a period is a metacharacter, it needs to be escaped to match
569 as an ordinary period. Because, for example, \f(CW\*(C`\ed\*(C'\fR and \f(CW\*(C`\ew\*(C'\fR are sets
570 of characters, it is incorrect to think of \f(CW\*(C`[^\ed\ew]\*(C'\fR as \f(CW\*(C`[\eD\eW]\*(C'\fR; in
571 fact \f(CW\*(C`[^\ed\ew]\*(C'\fR is the same as \f(CW\*(C`[^\ew]\*(C'\fR, which is the same as
572 \&\f(CW\*(C`[\eW]\*(C'\fR. Think De Morgan\*(Aqs laws.
573 .PP
574 In actuality, the period and \f(CW\*(C`\ed\es\ew\eD\eS\eW\*(C'\fR abbreviations are
575 themselves types of character classes, so the ones surrounded by
576 brackets are just one type of character class. When we need to make a
577 distinction, we refer to them as "bracketed character classes."
578 .PP
579 An anchor useful in basic regexps is the \fIword anchor\fR
580 \&\f(CW\*(C`\eb\*(C'\fR. This matches a boundary between a word character and a non\-word
581 character \f(CW\*(C`\ew\eW\*(C'\fR or \f(CW\*(C`\eW\ew\*(C'\fR:
582 .PP
583 .Vb 5
584 \& $x = "Housecat catenates house and cat";
585 \& $x =~ /cat/; # matches cat in \*(Aqhousecat\*(Aq
586 \& $x =~ /\ebcat/; # matches cat in \*(Aqcatenates\*(Aq
587 \& $x =~ /cat\eb/; # matches cat in \*(Aqhousecat\*(Aq
588 \& $x =~ /\ebcat\eb/; # matches \*(Aqcat\*(Aq at end of string
589 .Ve
590 .PP
591 Note in the last example, the end of the string is considered a word
592 boundary.
593 .PP
594 For natural language processing (so that, for example, apostrophes are
595 included in words), use instead \f(CW\*(C`\eb{wb}\*(C'\fR
596 .PP
597 .Vb 1
598 \& "don\*(Aqt" =~ / .+? \eb{wb} /x; # matches the whole string
599 .Ve
600 .PP
601 You might wonder why \f(CW\*(Aq.\*(Aq\fR matches everything but \f(CW"\en"\fR \- why not
602 every character? The reason is that often one is matching against
603 lines and would like to ignore the newline characters. For instance,
604 while the string \f(CW"\en"\fR represents one line, we would like to think
605 of it as empty. Then
606 .PP
607 .Vb 2
608 \& "" =~ /^$/; # matches
609 \& "\en" =~ /^$/; # matches, $ anchors before "\en"
610 \&
611 \& "" =~ /./; # doesn\*(Aqt match; it needs a char
612 \& "" =~ /^.$/; # doesn\*(Aqt match; it needs a char
613 \& "\en" =~ /^.$/; # doesn\*(Aqt match; it needs a char other than "\en"
614 \& "a" =~ /^.$/; # matches
615 \& "a\en" =~ /^.$/; # matches, $ anchors before "\en"
616 .Ve
617 .PP
618 This behavior is convenient, because we usually want to ignore
619 newlines when we count and match characters in a line. Sometimes,
620 however, we want to keep track of newlines. We might even want \f(CW\*(Aq^\*(Aq\fR
621 and \f(CW\*(Aq$\*(Aq\fR to anchor at the beginning and end of lines within the
622 string, rather than just the beginning and end of the string. Perl
623 allows us to choose between ignoring and paying attention to newlines
624 by using the \f(CW\*(C`/s\*(C'\fR and \f(CW\*(C`/m\*(C'\fR modifiers. \f(CW\*(C`/s\*(C'\fR and \f(CW\*(C`/m\*(C'\fR stand for
625 single line and multi\-line and they determine whether a string is to
626 be treated as one continuous string, or as a set of lines. The two
627 modifiers affect two aspects of how the regexp is interpreted: 1) how
628 the \f(CW\*(Aq.\*(Aq\fR character class is defined, and 2) where the anchors \f(CW\*(Aq^\*(Aq\fR
629 and \f(CW\*(Aq$\*(Aq\fR are able to match. Here are the four possible combinations:
630 .IP \(bu 4
631 no modifiers: Default behavior. \f(CW\*(Aq.\*(Aq\fR matches any character
632 except \f(CW"\en"\fR. \f(CW\*(Aq^\*(Aq\fR matches only at the beginning of the string and
633 \&\f(CW\*(Aq$\*(Aq\fR matches only at the end or before a newline at the end.
634 .IP \(bu 4
635 s modifier (\f(CW\*(C`/s\*(C'\fR): Treat string as a single long line. \f(CW\*(Aq.\*(Aq\fR matches
636 any character, even \f(CW"\en"\fR. \f(CW\*(Aq^\*(Aq\fR matches only at the beginning of
637 the string and \f(CW\*(Aq$\*(Aq\fR matches only at the end or before a newline at the
638 end.
639 .IP \(bu 4
640 m modifier (\f(CW\*(C`/m\*(C'\fR): Treat string as a set of multiple lines. \f(CW\*(Aq.\*(Aq\fR
641 matches any character except \f(CW"\en"\fR. \f(CW\*(Aq^\*(Aq\fR and \f(CW\*(Aq$\*(Aq\fR are able to match
642 at the start or end of \fIany\fR line within the string.
643 .IP \(bu 4
644 both s and m modifiers (\f(CW\*(C`/sm\*(C'\fR): Treat string as a single long line, but
645 detect multiple lines. \f(CW\*(Aq.\*(Aq\fR matches any character, even
646 \&\f(CW"\en"\fR. \f(CW\*(Aq^\*(Aq\fR and \f(CW\*(Aq$\*(Aq\fR, however, are able to match at the start or end
647 of \fIany\fR line within the string.
648 .PP
649 Here are examples of \f(CW\*(C`/s\*(C'\fR and \f(CW\*(C`/m\*(C'\fR in action:
650 .PP
651 .Vb 1
652 \& $x = "There once was a girl\enWho programmed in Perl\en";
653 \&
654 \& $x =~ /^Who/; # doesn\*(Aqt match, "Who" not at start of string
655 \& $x =~ /^Who/s; # doesn\*(Aqt match, "Who" not at start of string
656 \& $x =~ /^Who/m; # matches, "Who" at start of second line
657 \& $x =~ /^Who/sm; # matches, "Who" at start of second line
658 \&
659 \& $x =~ /girl.Who/; # doesn\*(Aqt match, "." doesn\*(Aqt match "\en"
660 \& $x =~ /girl.Who/s; # matches, "." matches "\en"
661 \& $x =~ /girl.Who/m; # doesn\*(Aqt match, "." doesn\*(Aqt match "\en"
662 \& $x =~ /girl.Who/sm; # matches, "." matches "\en"
663 .Ve
664 .PP
665 Most of the time, the default behavior is what is wanted, but \f(CW\*(C`/s\*(C'\fR and
666 \&\f(CW\*(C`/m\*(C'\fR are occasionally very useful. If \f(CW\*(C`/m\*(C'\fR is being used, the start
667 of the string can still be matched with \f(CW\*(C`\eA\*(C'\fR and the end of the string
668 can still be matched with the anchors \f(CW\*(C`\eZ\*(C'\fR (matches both the end and
669 the newline before, like \f(CW\*(Aq$\*(Aq\fR), and \f(CW\*(C`\ez\*(C'\fR (matches only the end):
670 .PP
671 .Vb 2
672 \& $x =~ /^Who/m; # matches, "Who" at start of second line
673 \& $x =~ /\eAWho/m; # doesn\*(Aqt match, "Who" is not at start of string
674 \&
675 \& $x =~ /girl$/m; # matches, "girl" at end of first line
676 \& $x =~ /girl\eZ/m; # doesn\*(Aqt match, "girl" is not at end of string
677 \&
678 \& $x =~ /Perl\eZ/m; # matches, "Perl" is at newline before end
679 \& $x =~ /Perl\ez/m; # doesn\*(Aqt match, "Perl" is not at end of string
680 .Ve
681 .PP
682 We now know how to create choices among classes of characters in a
683 regexp. What about choices among words or character strings? Such
684 choices are described in the next section.
685 .SS "Matching this or that"
686 .IX Subsection "Matching this or that"
687 Sometimes we would like our regexp to be able to match different
688 possible words or character strings. This is accomplished by using
689 the \fIalternation\fR metacharacter \f(CW\*(Aq|\*(Aq\fR. To match \f(CW\*(C`dog\*(C'\fR or \f(CW\*(C`cat\*(C'\fR, we
690 form the regexp \f(CW\*(C`dog|cat\*(C'\fR. As before, Perl will try to match the
691 regexp at the earliest possible point in the string. At each
692 character position, Perl will first try to match the first
693 alternative, \f(CW\*(C`dog\*(C'\fR. If \f(CW\*(C`dog\*(C'\fR doesn\*(Aqt match, Perl will then try the
694 next alternative, \f(CW\*(C`cat\*(C'\fR. If \f(CW\*(C`cat\*(C'\fR doesn\*(Aqt match either, then the
695 match fails and Perl moves to the next position in the string. Some
696 examples:
697 .PP
698 .Vb 2
699 \& "cats and dogs" =~ /cat|dog|bird/; # matches "cat"
700 \& "cats and dogs" =~ /dog|cat|bird/; # matches "cat"
701 .Ve
702 .PP
703 Even though \f(CW\*(C`dog\*(C'\fR is the first alternative in the second regexp,
704 \&\f(CW\*(C`cat\*(C'\fR is able to match earlier in the string.
705 .PP
706 .Vb 2
707 \& "cats" =~ /c|ca|cat|cats/; # matches "c"
708 \& "cats" =~ /cats|cat|ca|c/; # matches "cats"
709 .Ve
710 .PP
711 Here, all the alternatives match at the first string position, so the
712 first alternative is the one that matches. If some of the
713 alternatives are truncations of the others, put the longest ones first
714 to give them a chance to match.
715 .PP
716 .Vb 2
717 \& "cab" =~ /a|b|c/ # matches "c"
718 \& # /a|b|c/ == /[abc]/
719 .Ve
720 .PP
721 The last example points out that character classes are like
722 alternations of characters. At a given character position, the first
723 alternative that allows the regexp match to succeed will be the one
724 that matches.
725 .SS "Grouping things and hierarchical matching"
726 .IX Subsection "Grouping things and hierarchical matching"
727 Alternation allows a regexp to choose among alternatives, but by
728 itself it is unsatisfying. The reason is that each alternative is a whole
729 regexp, but sometimes we want alternatives for just part of a
730 regexp. For instance, suppose we want to search for housecats or
731 housekeepers. The regexp \f(CW\*(C`housecat|housekeeper\*(C'\fR fits the bill, but is
732 inefficient because we had to type \f(CW\*(C`house\*(C'\fR twice. It would be nice to
733 have parts of the regexp be constant, like \f(CW\*(C`house\*(C'\fR, and some
734 parts have alternatives, like \f(CW\*(C`cat|keeper\*(C'\fR.
735 .PP
736 The \fIgrouping\fR metacharacters \f(CW\*(C`()\*(C'\fR solve this problem. Grouping
737 allows parts of a regexp to be treated as a single unit. Parts of a
738 regexp are grouped by enclosing them in parentheses. Thus we could solve
739 the \f(CW\*(C`housecat|housekeeper\*(C'\fR by forming the regexp as
740 \&\f(CWhouse(cat|keeper)\fR. The regexp \f(CWhouse(cat|keeper)\fR means match
741 \&\f(CW\*(C`house\*(C'\fR followed by either \f(CW\*(C`cat\*(C'\fR or \f(CW\*(C`keeper\*(C'\fR. Some more examples
742 are
743 .PP
744 .Vb 4
745 \& /(a|b)b/; # matches \*(Aqab\*(Aq or \*(Aqbb\*(Aq
746 \& /(ac|b)b/; # matches \*(Aqacb\*(Aq or \*(Aqbb\*(Aq
747 \& /(^a|b)c/; # matches \*(Aqac\*(Aq at start of string or \*(Aqbc\*(Aq anywhere
748 \& /(a|[bc])d/; # matches \*(Aqad\*(Aq, \*(Aqbd\*(Aq, or \*(Aqcd\*(Aq
749 \&
750 \& /house(cat|)/; # matches either \*(Aqhousecat\*(Aq or \*(Aqhouse\*(Aq
751 \& /house(cat(s|)|)/; # matches either \*(Aqhousecats\*(Aq or \*(Aqhousecat\*(Aq or
752 \& # \*(Aqhouse\*(Aq. Note groups can be nested.
753 \&
754 \& /(19|20|)\ed\ed/; # match years 19xx, 20xx, or the Y2K problem, xx
755 \& "20" =~ /(19|20|)\ed\ed/; # matches the null alternative \*(Aq()\ed\ed\*(Aq,
756 \& # because \*(Aq20\ed\ed\*(Aq can\*(Aqt match
757 .Ve
758 .PP
759 Alternations behave the same way in groups as out of them: at a given
760 string position, the leftmost alternative that allows the regexp to
761 match is taken. So in the last example at the first string position,
762 \&\f(CW"20"\fR matches the second alternative, but there is nothing left over
763 to match the next two digits \f(CW\*(C`\ed\ed\*(C'\fR. So Perl moves on to the next
764 alternative, which is the null alternative and that works, since
765 \&\f(CW"20"\fR is two digits.
766 .PP
767 The process of trying one alternative, seeing if it matches, and
768 moving on to the next alternative, while going back in the string
769 from where the previous alternative was tried, if it doesn\*(Aqt, is called
770 \&\fIbacktracking\fR. The term "backtracking" comes from the idea that
771 matching a regexp is like a walk in the woods. Successfully matching
772 a regexp is like arriving at a destination. There are many possible
773 trailheads, one for each string position, and each one is tried in
774 order, left to right. From each trailhead there may be many paths,
775 some of which get you there, and some which are dead ends. When you
776 walk along a trail and hit a dead end, you have to backtrack along the
777 trail to an earlier point to try another trail. If you hit your
778 destination, you stop immediately and forget about trying all the
779 other trails. You are persistent, and only if you have tried all the
780 trails from all the trailheads and not arrived at your destination, do
781 you declare failure. To be concrete, here is a step\-by\-step analysis
782 of what Perl does when it tries to match the regexp
783 .PP
784 .Vb 1
785 \& "abcde" =~ /(abd|abc)(df|d|de)/;
786 .Ve
787 .IP 1. 4
788 Start with the first letter in the string \f(CW\*(Aqa\*(Aq\fR.
789 .IP 2. 4
790 Try the first alternative in the first group \f(CW\*(Aqabd\*(Aq\fR.
791 .IP 3. 4
792 Match \f(CW\*(Aqa\*(Aq\fR followed by \f(CW\*(Aqb\*(Aq\fR. So far so good.
793 .IP 4. 4
794 \&\f(CW\*(Aqd\*(Aq\fR in the regexp doesn\*(Aqt match \f(CW\*(Aqc\*(Aq\fR in the string \- a
795 dead end. So backtrack two characters and pick the second alternative
796 in the first group \f(CW\*(Aqabc\*(Aq\fR.
797 .IP 5. 4
798 Match \f(CW\*(Aqa\*(Aq\fR followed by \f(CW\*(Aqb\*(Aq\fR followed by \f(CW\*(Aqc\*(Aq\fR. We are on a roll
799 and have satisfied the first group. Set \f(CW$1\fR to \f(CW\*(Aqabc\*(Aq\fR.
800 .IP 6. 4
801 Move on to the second group and pick the first alternative \f(CW\*(Aqdf\*(Aq\fR.
802 .IP 7. 4
803 Match the \f(CW\*(Aqd\*(Aq\fR.
804 .IP 8. 4
805 \&\f(CW\*(Aqf\*(Aq\fR in the regexp doesn\*(Aqt match \f(CW\*(Aqe\*(Aq\fR in the string, so a dead
806 end. Backtrack one character and pick the second alternative in the
807 second group \f(CW\*(Aqd\*(Aq\fR.
808 .IP 9. 4
809 \&\f(CW\*(Aqd\*(Aq\fR matches. The second grouping is satisfied, so set
810 \&\f(CW$2\fR to \f(CW\*(Aqd\*(Aq\fR.
811 .IP 10. 4
812 We are at the end of the regexp, so we are done! We have
813 matched \f(CW\*(Aqabcd\*(Aq\fR out of the string \f(CW"abcde"\fR.
814 .PP
815 There are a couple of things to note about this analysis. First, the
816 third alternative in the second group \f(CW\*(Aqde\*(Aq\fR also allows a match, but we
817 stopped before we got to it \- at a given character position, leftmost
818 wins. Second, we were able to get a match at the first character
819 position of the string \f(CW\*(Aqa\*(Aq\fR. If there were no matches at the first
820 position, Perl would move to the second character position \f(CW\*(Aqb\*(Aq\fR and
821 attempt the match all over again. Only when all possible paths at all
822 possible character positions have been exhausted does Perl give
823 up and declare \f(CW\*(C`$string\ =~\ /(abd|abc)(df|d|de)/;\*(C'\fR to be false.
824 .PP
825 Even with all this work, regexp matching happens remarkably fast. To
826 speed things up, Perl compiles the regexp into a compact sequence of
827 opcodes that can often fit inside a processor cache. When the code is
828 executed, these opcodes can then run at full throttle and search very
829 quickly.
830 .SS "Extracting matches"
831 .IX Subsection "Extracting matches"
832 The grouping metacharacters \f(CW\*(C`()\*(C'\fR also serve another completely
833 different function: they allow the extraction of the parts of a string
834 that matched. This is very useful to find out what matched and for
835 text processing in general. For each grouping, the part that matched
836 inside goes into the special variables \f(CW$1\fR, \f(CW$2\fR, \fIetc\fR. They can be
837 used just as ordinary variables:
838 .PP
839 .Vb 6
840 \& # extract hours, minutes, seconds
841 \& if ($time =~ /(\ed\ed):(\ed\ed):(\ed\ed)/) { # match hh:mm:ss format
842 \& $hours = $1;
843 \& $minutes = $2;
844 \& $seconds = $3;
845 \& }
846 .Ve
847 .PP
848 Now, we know that in scalar context,
849 \&\f(CW\*(C`$time\ =~\ /(\ed\ed):(\ed\ed):(\ed\ed)/\*(C'\fR returns a true or false
850 value. In list context, however, it returns the list of matched values
851 \&\f(CW\*(C`($1,$2,$3)\*(C'\fR. So we could write the code more compactly as
852 .PP
853 .Vb 2
854 \& # extract hours, minutes, seconds
855 \& ($hours, $minutes, $second) = ($time =~ /(\ed\ed):(\ed\ed):(\ed\ed)/);
856 .Ve
857 .PP
858 If the groupings in a regexp are nested, \f(CW$1\fR gets the group with the
859 leftmost opening parenthesis, \f(CW$2\fR the next opening parenthesis,
860 \&\fIetc\fR. Here is a regexp with nested groups:
861 .PP
862 .Vb 2
863 \& /(ab(cd|ef)((gi)|j))/;
864 \& 1 2 34
865 .Ve
866 .PP
867 If this regexp matches, \f(CW$1\fR contains a string starting with
868 \&\f(CW\*(Aqab\*(Aq\fR, \f(CW$2\fR is either set to \f(CW\*(Aqcd\*(Aq\fR or \f(CW\*(Aqef\*(Aq\fR, \f(CW$3\fR equals either
869 \&\f(CW\*(Aqgi\*(Aq\fR or \f(CW\*(Aqj\*(Aq\fR, and \f(CW$4\fR is either set to \f(CW\*(Aqgi\*(Aq\fR, just like \f(CW$3\fR,
870 or it remains undefined.
871 .PP
872 For convenience, Perl sets \f(CW$+\fR to the string held by the highest numbered
873 \&\f(CW$1\fR, \f(CW$2\fR,... that got assigned (and, somewhat related, \f(CW$^N\fR to the
874 value of the \f(CW$1\fR, \f(CW$2\fR,... most\-recently assigned; \fIi.e.\fR the \f(CW$1\fR,
875 \&\f(CW$2\fR,... associated with the rightmost closing parenthesis used in the
876 match).
877 .SS Backreferences
878 .IX Subsection "Backreferences"
879 Closely associated with the matching variables \f(CW$1\fR, \f(CW$2\fR, ... are
880 the \fIbackreferences\fR \f(CW\*(C`\eg1\*(C'\fR, \f(CW\*(C`\eg2\*(C'\fR,... Backreferences are simply
881 matching variables that can be used \fIinside\fR a regexp. This is a
882 really nice feature; what matches later in a regexp is made to depend on
883 what matched earlier in the regexp. Suppose we wanted to look
884 for doubled words in a text, like "the the". The following regexp finds
885 all 3\-letter doubles with a space in between:
886 .PP
887 .Vb 1
888 \& /\eb(\ew\ew\ew)\es\eg1\eb/;
889 .Ve
890 .PP
891 The grouping assigns a value to \f(CW\*(C`\eg1\*(C'\fR, so that the same 3\-letter sequence
892 is used for both parts.
893 .PP
894 A similar task is to find words consisting of two identical parts:
895 .PP
896 .Vb 7
897 \& % simple_grep \*(Aq^(\ew\ew\ew\ew|\ew\ew\ew|\ew\ew|\ew)\eg1$\*(Aq /usr/dict/words
898 \& beriberi
899 \& booboo
900 \& coco
901 \& mama
902 \& murmur
903 \& papa
904 .Ve
905 .PP
906 The regexp has a single grouping which considers 4\-letter
907 combinations, then 3\-letter combinations, \fIetc\fR., and uses \f(CW\*(C`\eg1\*(C'\fR to look for
908 a repeat. Although \f(CW$1\fR and \f(CW\*(C`\eg1\*(C'\fR represent the same thing, care should be
909 taken to use matched variables \f(CW$1\fR, \f(CW$2\fR,... only \fIoutside\fR a regexp
910 and backreferences \f(CW\*(C`\eg1\*(C'\fR, \f(CW\*(C`\eg2\*(C'\fR,... only \fIinside\fR a regexp; not doing
911 so may lead to surprising and unsatisfactory results.
912 .SS "Relative backreferences"
913 .IX Subsection "Relative backreferences"
914 Counting the opening parentheses to get the correct number for a
915 backreference is error\-prone as soon as there is more than one
916 capturing group. A more convenient technique became available
917 with Perl 5.10: relative backreferences. To refer to the immediately
918 preceding capture group one now may write \f(CW\*(C`\eg\-1\*(C'\fR or \f(CW\*(C`\eg{\-1}\*(C'\fR, the next but
919 last is available via \f(CW\*(C`\eg\-2\*(C'\fR or \f(CW\*(C`\eg{\-2}\*(C'\fR, and so on.
920 .PP
921 Another good reason in addition to readability and maintainability
922 for using relative backreferences is illustrated by the following example,
923 where a simple pattern for matching peculiar strings is used:
924 .PP
925 .Vb 1
926 \& $a99a = \*(Aq([a\-z])(\ed)\eg2\eg1\*(Aq; # matches a11a, g22g, x33x, etc.
927 .Ve
928 .PP
929 Now that we have this pattern stored as a handy string, we might feel
930 tempted to use it as a part of some other pattern:
931 .PP
932 .Vb 6
933 \& $line = "code=e99e";
934 \& if ($line =~ /^(\ew+)=$a99a$/){ # unexpected behavior!
935 \& print "$1 is valid\en";
936 \& } else {
937 \& print "bad line: \*(Aq$line\*(Aq\en";
938 \& }
939 .Ve
940 .PP
941 But this doesn\*(Aqt match, at least not the way one might expect. Only
942 after inserting the interpolated \f(CW$a99a\fR and looking at the resulting
943 full text of the regexp is it obvious that the backreferences have
944 backfired. The subexpression \f(CW\*(C`(\ew+)\*(C'\fR has snatched number 1 and
945 demoted the groups in \f(CW$a99a\fR by one rank. This can be avoided by
946 using relative backreferences:
947 .PP
948 .Vb 1
949 \& $a99a = \*(Aq([a\-z])(\ed)\eg{\-1}\eg{\-2}\*(Aq; # safe for being interpolated
950 .Ve
951 .SS "Named backreferences"
952 .IX Subsection "Named backreferences"
953 Perl 5.10 also introduced named capture groups and named backreferences.
954 To attach a name to a capturing group, you write either
955 \&\f(CW\*(C`(?<name>...)\*(C'\fR or \f(CW\*(C`(?\*(Aqname\*(Aq...)\*(C'\fR. The backreference may
956 then be written as \f(CW\*(C`\eg{name}\*(C'\fR. It is permissible to attach the
957 same name to more than one group, but then only the leftmost one of the
958 eponymous set can be referenced. Outside of the pattern a named
959 capture group is accessible through the \f(CW\*(C`%+\*(C'\fR hash.
960 .PP
961 Assuming that we have to match calendar dates which may be given in one
962 of the three formats yyyy\-mm\-dd, mm/dd/yyyy or dd.mm.yyyy, we can write
963 three suitable patterns where we use \f(CW\*(Aqd\*(Aq\fR, \f(CW\*(Aqm\*(Aq\fR and \f(CW\*(Aqy\*(Aq\fR respectively as the
964 names of the groups capturing the pertaining components of a date. The
965 matching operation combines the three patterns as alternatives:
966 .PP
967 .Vb 8
968 \& $fmt1 = \*(Aq(?<y>\ed\ed\ed\ed)\-(?<m>\ed\ed)\-(?<d>\ed\ed)\*(Aq;
969 \& $fmt2 = \*(Aq(?<m>\ed\ed)/(?<d>\ed\ed)/(?<y>\ed\ed\ed\ed)\*(Aq;
970 \& $fmt3 = \*(Aq(?<d>\ed\ed)\e.(?<m>\ed\ed)\e.(?<y>\ed\ed\ed\ed)\*(Aq;
971 \& for my $d (qw(2006\-10\-21 15.01.2007 10/31/2005)) {
972 \& if ( $d =~ m{$fmt1|$fmt2|$fmt3} ){
973 \& print "day=$+{d} month=$+{m} year=$+{y}\en";
974 \& }
975 \& }
976 .Ve
977 .PP
978 If any of the alternatives matches, the hash \f(CW\*(C`%+\*(C'\fR is bound to contain the
979 three key\-value pairs.
980 .SS "Alternative capture group numbering"
981 .IX Subsection "Alternative capture group numbering"
982 Yet another capturing group numbering technique (also as from Perl 5.10)
983 deals with the problem of referring to groups within a set of alternatives.
984 Consider a pattern for matching a time of the day, civil or military style:
985 .PP
986 .Vb 3
987 \& if ( $time =~ /(\ed\ed|\ed):(\ed\ed)|(\ed\ed)(\ed\ed)/ ){
988 \& # process hour and minute
989 \& }
990 .Ve
991 .PP
992 Processing the results requires an additional if statement to determine
993 whether \f(CW$1\fR and \f(CW$2\fR or \f(CW$3\fR and \f(CW$4\fR contain the goodies. It would
994 be easier if we could use group numbers 1 and 2 in second alternative as
995 well, and this is exactly what the parenthesized construct \f(CW\*(C`(?|...)\*(C'\fR,
996 set around an alternative achieves. Here is an extended version of the
997 previous pattern:
998 .PP
999 .Vb 3
1000 \& if($time =~ /(?|(\ed\ed|\ed):(\ed\ed)|(\ed\ed)(\ed\ed))\es+([A\-Z][A\-Z][A\-Z])/){
1001 \& print "hour=$1 minute=$2 zone=$3\en";
1002 \& }
1003 .Ve
1004 .PP
1005 Within the alternative numbering group, group numbers start at the same
1006 position for each alternative. After the group, numbering continues
1007 with one higher than the maximum reached across all the alternatives.
1008 .SS "Position information"
1009 .IX Subsection "Position information"
1010 In addition to what was matched, Perl also provides the
1011 positions of what was matched as contents of the \f(CW\*(C`@\-\*(C'\fR and \f(CW\*(C`@+\*(C'\fR
1012 arrays. \f(CW\*(C`$\-[0]\*(C'\fR is the position of the start of the entire match and
1013 \&\f(CW$+[0]\fR is the position of the end. Similarly, \f(CW\*(C`$\-[n]\*(C'\fR is the
1014 position of the start of the \f(CW$n\fR match and \f(CW$+[n]\fR is the position
1015 of the end. If \f(CW$n\fR is undefined, so are \f(CW\*(C`$\-[n]\*(C'\fR and \f(CW$+[n]\fR. Then
1016 this code
1017 .PP
1018 .Vb 6
1019 \& $x = "Mmm...donut, thought Homer";
1020 \& $x =~ /^(Mmm|Yech)\e.\e.\e.(donut|peas)/; # matches
1021 \& foreach $exp (1..$#\-) {
1022 \& no strict \*(Aqrefs\*(Aq;
1023 \& print "Match $exp: \*(Aq$$exp\*(Aq at position ($\-[$exp],$+[$exp])\en";
1024 \& }
1025 .Ve
1026 .PP
1027 prints
1028 .PP
1029 .Vb 2
1030 \& Match 1: \*(AqMmm\*(Aq at position (0,3)
1031 \& Match 2: \*(Aqdonut\*(Aq at position (6,11)
1032 .Ve
1033 .PP
1034 Even if there are no groupings in a regexp, it is still possible to
1035 find out what exactly matched in a string. If you use them, Perl
1036 will set \f(CW\*(C`$\`\*(C'\fR to the part of the string before the match, will set \f(CW$&\fR
1037 to the part of the string that matched, and will set \f(CW\*(C`$\*(Aq\*(C'\fR to the part
1038 of the string after the match. An example:
1039 .PP
1040 .Vb 3
1041 \& $x = "the cat caught the mouse";
1042 \& $x =~ /cat/; # $\` = \*(Aqthe \*(Aq, $& = \*(Aqcat\*(Aq, $\*(Aq = \*(Aq caught the mouse\*(Aq
1043 \& $x =~ /the/; # $\` = \*(Aq\*(Aq, $& = \*(Aqthe\*(Aq, $\*(Aq = \*(Aq cat caught the mouse\*(Aq
1044 .Ve
1045 .PP
1046 In the second match, \f(CW\*(C`$\`\*(C'\fR equals \f(CW\*(Aq\*(Aq\fR because the regexp matched at the
1047 first character position in the string and stopped; it never saw the
1048 second "the".
1049 .PP
1050 If your code is to run on Perl versions earlier than
1051 5.20, it is worthwhile to note that using \f(CW\*(C`$\`\*(C'\fR and \f(CW\*(C`$\*(Aq\*(C'\fR
1052 slows down regexp matching quite a bit, while \f(CW$&\fR slows it down to a
1053 lesser extent, because if they are used in one regexp in a program,
1054 they are generated for \fIall\fR regexps in the program. So if raw
1055 performance is a goal of your application, they should be avoided.
1056 If you need to extract the corresponding substrings, use \f(CW\*(C`@\-\*(C'\fR and
1057 \&\f(CW\*(C`@+\*(C'\fR instead:
1058 .PP
1059 .Vb 3
1060 \& $\` is the same as substr( $x, 0, $\-[0] )
1061 \& $& is the same as substr( $x, $\-[0], $+[0]\-$\-[0] )
1062 \& $\*(Aq is the same as substr( $x, $+[0] )
1063 .Ve
1064 .PP
1065 As of Perl 5.10, the \f(CW\*(C`${^PREMATCH}\*(C'\fR, \f(CW\*(C`${^MATCH}\*(C'\fR and \f(CW\*(C`${^POSTMATCH}\*(C'\fR
1066 variables may be used. These are only set if the \f(CW\*(C`/p\*(C'\fR modifier is
1067 present. Consequently they do not penalize the rest of the program. In
1068 Perl 5.20, \f(CW\*(C`${^PREMATCH}\*(C'\fR, \f(CW\*(C`${^MATCH}\*(C'\fR and \f(CW\*(C`${^POSTMATCH}\*(C'\fR are available
1069 whether the \f(CW\*(C`/p\*(C'\fR has been used or not (the modifier is ignored), and
1070 \&\f(CW\*(C`$\`\*(C'\fR, \f(CW\*(C`$\*(Aq\*(C'\fR and \f(CW$&\fR do not cause any speed difference.
1071 .SS "Non\-capturing groupings"
1072 .IX Subsection "Non-capturing groupings"
1073 A group that is required to bundle a set of alternatives may or may not be
1074 useful as a capturing group. If it isn\*(Aqt, it just creates a superfluous
1075 addition to the set of available capture group values, inside as well as
1076 outside the regexp. Non\-capturing groupings, denoted by \f(CW\*(C`(?:regexp)\*(C'\fR,
1077 still allow the regexp to be treated as a single unit, but don\*(Aqt establish
1078 a capturing group at the same time. Both capturing and non\-capturing
1079 groupings are allowed to co\-exist in the same regexp. Because there is
1080 no extraction, non\-capturing groupings are faster than capturing
1081 groupings. Non\-capturing groupings are also handy for choosing exactly
1082 which parts of a regexp are to be extracted to matching variables:
1083 .PP
1084 .Vb 2
1085 \& # match a number, $1\-$4 are set, but we only want $1
1086 \& /([+\-]?\e *(\ed+(\e.\ed*)?|\e.\ed+)([eE][+\-]?\ed+)?)/;
1087 \&
1088 \& # match a number faster , only $1 is set
1089 \& /([+\-]?\e *(?:\ed+(?:\e.\ed*)?|\e.\ed+)(?:[eE][+\-]?\ed+)?)/;
1090 \&
1091 \& # match a number, get $1 = whole number, $2 = exponent
1092 \& /([+\-]?\e *(?:\ed+(?:\e.\ed*)?|\e.\ed+)(?:[eE]([+\-]?\ed+))?)/;
1093 .Ve
1094 .PP
1095 Non\-capturing groupings are also useful for removing nuisance
1096 elements gathered from a split operation where parentheses are
1097 required for some reason:
1098 .PP
1099 .Vb 3
1100 \& $x = \*(Aq12aba34ba5\*(Aq;
1101 \& @num = split /(a|b)+/, $x; # @num = (\*(Aq12\*(Aq,\*(Aqa\*(Aq,\*(Aq34\*(Aq,\*(Aqa\*(Aq,\*(Aq5\*(Aq)
1102 \& @num = split /(?:a|b)+/, $x; # @num = (\*(Aq12\*(Aq,\*(Aq34\*(Aq,\*(Aq5\*(Aq)
1103 .Ve
1104 .PP
1105 In Perl 5.22 and later, all groups within a regexp can be set to
1106 non\-capturing by using the new \f(CW\*(C`/n\*(C'\fR flag:
1107 .PP
1108 .Vb 1
1109 \& "hello" =~ /(hi|hello)/n; # $1 is not set!
1110 .Ve
1111 .PP
1112 See "n" in perlre for more information.
1113 .SS "Matching repetitions"
1114 .IX Subsection "Matching repetitions"
1115 The examples in the previous section display an annoying weakness. We
1116 were only matching 3\-letter words, or chunks of words of 4 letters or
1117 less. We\*(Aqd like to be able to match words or, more generally, strings
1118 of any length, without writing out tedious alternatives like
1119 \&\f(CW\*(C`\ew\ew\ew\ew|\ew\ew\ew|\ew\ew|\ew\*(C'\fR.
1120 .PP
1121 This is exactly the problem the \fIquantifier\fR metacharacters \f(CW\*(Aq?\*(Aq\fR,
1122 \&\f(CW\*(Aq*\*(Aq\fR, \f(CW\*(Aq+\*(Aq\fR, and \f(CW\*(C`{}\*(C'\fR were created for. They allow us to delimit the
1123 number of repeats for a portion of a regexp we consider to be a
1124 match. Quantifiers are put immediately after the character, character
1125 class, or grouping that we want to specify. They have the following
1126 meanings:
1127 .IP \(bu 4
1128 \&\f(CW\*(C`a?\*(C'\fR means: match \f(CW\*(Aqa\*(Aq\fR 1 or 0 times
1129 .IP \(bu 4
1130 \&\f(CW\*(C`a*\*(C'\fR means: match \f(CW\*(Aqa\*(Aq\fR 0 or more times, \fIi.e.\fR, any number of times
1131 .IP \(bu 4
1132 \&\f(CW\*(C`a+\*(C'\fR means: match \f(CW\*(Aqa\*(Aq\fR 1 or more times, \fIi.e.\fR, at least once
1133 .IP \(bu 4
1134 \&\f(CW\*(C`a{n,m}\*(C'\fR means: match at least \f(CW\*(C`n\*(C'\fR times, but not more than \f(CW\*(C`m\*(C'\fR
1135 times.
1136 .IP \(bu 4
1137 \&\f(CW\*(C`a{n,}\*(C'\fR means: match at least \f(CW\*(C`n\*(C'\fR or more times
1138 .IP \(bu 4
1139 \&\f(CW\*(C`a{,n}\*(C'\fR means: match at most \f(CW\*(C`n\*(C'\fR times, or fewer
1140 .IP \(bu 4
1141 \&\f(CW\*(C`a{n}\*(C'\fR means: match exactly \f(CW\*(C`n\*(C'\fR times
1142 .PP
1143 If you like, you can add blanks (tab or space characters) within the
1144 braces, but adjacent to them, and/or next to the comma (if any).
1145 .PP
1146 Here are some examples:
1147 .PP
1148 .Vb 10
1149 \& /[a\-z]+\es+\ed*/; # match a lowercase word, at least one space, and
1150 \& # any number of digits
1151 \& /(\ew+)\es+\eg1/; # match doubled words of arbitrary length
1152 \& /y(es)?/i; # matches \*(Aqy\*(Aq, \*(AqY\*(Aq, or a case\-insensitive \*(Aqyes\*(Aq
1153 \& $year =~ /^\ed{2,4}$/; # make sure year is at least 2 but not more
1154 \& # than 4 digits
1155 \& $year =~ /^\ed{ 2, 4 }$/; # Same; for those who like wide open
1156 \& # spaces.
1157 \& $year =~ /^\ed{2, 4}$/; # Same.
1158 \& $year =~ /^\ed{4}$|^\ed{2}$/; # better match; throw out 3\-digit dates
1159 \& $year =~ /^\ed{2}(\ed{2})?$/; # same thing written differently.
1160 \& # However, this captures the last two
1161 \& # digits in $1 and the other does not.
1162 \&
1163 \& % simple_grep \*(Aq^(\ew+)\eg1$\*(Aq /usr/dict/words # isn\*(Aqt this easier?
1164 \& beriberi
1165 \& booboo
1166 \& coco
1167 \& mama
1168 \& murmur
1169 \& papa
1170 .Ve
1171 .PP
1172 For all of these quantifiers, Perl will try to match as much of the
1173 string as possible, while still allowing the regexp to succeed. Thus
1174 with \f(CW\*(C`/a?.../\*(C'\fR, Perl will first try to match the regexp with the \f(CW\*(Aqa\*(Aq\fR
1175 present; if that fails, Perl will try to match the regexp without the
1176 \&\f(CW\*(Aqa\*(Aq\fR present. For the quantifier \f(CW\*(Aq*\*(Aq\fR, we get the following:
1177 .PP
1178 .Vb 5
1179 \& $x = "the cat in the hat";
1180 \& $x =~ /^(.*)(cat)(.*)$/; # matches,
1181 \& # $1 = \*(Aqthe \*(Aq
1182 \& # $2 = \*(Aqcat\*(Aq
1183 \& # $3 = \*(Aq in the hat\*(Aq
1184 .Ve
1185 .PP
1186 Which is what we might expect, the match finds the only \f(CW\*(C`cat\*(C'\fR in the
1187 string and locks onto it. Consider, however, this regexp:
1188 .PP
1189 .Vb 4
1190 \& $x =~ /^(.*)(at)(.*)$/; # matches,
1191 \& # $1 = \*(Aqthe cat in the h\*(Aq
1192 \& # $2 = \*(Aqat\*(Aq
1193 \& # $3 = \*(Aq\*(Aq (0 characters match)
1194 .Ve
1195 .PP
1196 One might initially guess that Perl would find the \f(CW\*(C`at\*(C'\fR in \f(CW\*(C`cat\*(C'\fR and
1197 stop there, but that wouldn\*(Aqt give the longest possible string to the
1198 first quantifier \f(CW\*(C`.*\*(C'\fR. Instead, the first quantifier \f(CW\*(C`.*\*(C'\fR grabs as
1199 much of the string as possible while still having the regexp match. In
1200 this example, that means having the \f(CW\*(C`at\*(C'\fR sequence with the final \f(CW\*(C`at\*(C'\fR
1201 in the string. The other important principle illustrated here is that,
1202 when there are two or more elements in a regexp, the \fIleftmost\fR
1203 quantifier, if there is one, gets to grab as much of the string as
1204 possible, leaving the rest of the regexp to fight over scraps. Thus in
1205 our example, the first quantifier \f(CW\*(C`.*\*(C'\fR grabs most of the string, while
1206 the second quantifier \f(CW\*(C`.*\*(C'\fR gets the empty string. Quantifiers that
1207 grab as much of the string as possible are called \fImaximal match\fR or
1208 \&\fIgreedy\fR quantifiers.
1209 .PP
1210 When a regexp can match a string in several different ways, we can use
1211 the principles above to predict which way the regexp will match:
1212 .IP \(bu 4
1213 Principle 0: Taken as a whole, any regexp will be matched at the
1214 earliest possible position in the string.
1215 .IP \(bu 4
1216 Principle 1: In an alternation \f(CW\*(C`a|b|c...\*(C'\fR, the leftmost alternative
1217 that allows a match for the whole regexp will be the one used.
1218 .IP \(bu 4
1219 Principle 2: The maximal matching quantifiers \f(CW\*(Aq?\*(Aq\fR, \f(CW\*(Aq*\*(Aq\fR, \f(CW\*(Aq+\*(Aq\fR and
1220 \&\f(CW\*(C`{n,m}\*(C'\fR will in general match as much of the string as possible while
1221 still allowing the whole regexp to match.
1222 .IP \(bu 4
1223 Principle 3: If there are two or more elements in a regexp, the
1224 leftmost greedy quantifier, if any, will match as much of the string
1225 as possible while still allowing the whole regexp to match. The next
1226 leftmost greedy quantifier, if any, will try to match as much of the
1227 string remaining available to it as possible, while still allowing the
1228 whole regexp to match. And so on, until all the regexp elements are
1229 satisfied.
1230 .PP
1231 As we have seen above, Principle 0 overrides the others. The regexp
1232 will be matched as early as possible, with the other principles
1233 determining how the regexp matches at that earliest character
1234 position.
1235 .PP
1236 Here is an example of these principles in action:
1237 .PP
1238 .Vb 5
1239 \& $x = "The programming republic of Perl";
1240 \& $x =~ /^(.+)(e|r)(.*)$/; # matches,
1241 \& # $1 = \*(AqThe programming republic of Pe\*(Aq
1242 \& # $2 = \*(Aqr\*(Aq
1243 \& # $3 = \*(Aql\*(Aq
1244 .Ve
1245 .PP
1246 This regexp matches at the earliest string position, \f(CW\*(AqT\*(Aq\fR. One
1247 might think that \f(CW\*(Aqe\*(Aq\fR, being leftmost in the alternation, would be
1248 matched, but \f(CW\*(Aqr\*(Aq\fR produces the longest string in the first quantifier.
1249 .PP
1250 .Vb 3
1251 \& $x =~ /(m{1,2})(.*)$/; # matches,
1252 \& # $1 = \*(Aqmm\*(Aq
1253 \& # $2 = \*(Aqing republic of Perl\*(Aq
1254 .Ve
1255 .PP
1256 Here, The earliest possible match is at the first \f(CW\*(Aqm\*(Aq\fR in
1257 \&\f(CW\*(C`programming\*(C'\fR. \f(CW\*(C`m{1,2}\*(C'\fR is the first quantifier, so it gets to match
1258 a maximal \f(CW\*(C`mm\*(C'\fR.
1259 .PP
1260 .Vb 3
1261 \& $x =~ /.*(m{1,2})(.*)$/; # matches,
1262 \& # $1 = \*(Aqm\*(Aq
1263 \& # $2 = \*(Aqing republic of Perl\*(Aq
1264 .Ve
1265 .PP
1266 Here, the regexp matches at the start of the string. The first
1267 quantifier \f(CW\*(C`.*\*(C'\fR grabs as much as possible, leaving just a single
1268 \&\f(CW\*(Aqm\*(Aq\fR for the second quantifier \f(CW\*(C`m{1,2}\*(C'\fR.
1269 .PP
1270 .Vb 4
1271 \& $x =~ /(.?)(m{1,2})(.*)$/; # matches,
1272 \& # $1 = \*(Aqa\*(Aq
1273 \& # $2 = \*(Aqmm\*(Aq
1274 \& # $3 = \*(Aqing republic of Perl\*(Aq
1275 .Ve
1276 .PP
1277 Here, \f(CW\*(C`.?\*(C'\fR eats its maximal one character at the earliest possible
1278 position in the string, \f(CW\*(Aqa\*(Aq\fR in \f(CW\*(C`programming\*(C'\fR, leaving \f(CW\*(C`m{1,2}\*(C'\fR
1279 the opportunity to match both \f(CW\*(Aqm\*(Aq\fR\*(Aqs. Finally,
1280 .PP
1281 .Vb 1
1282 \& "aXXXb" =~ /(X*)/; # matches with $1 = \*(Aq\*(Aq
1283 .Ve
1284 .PP
1285 because it can match zero copies of \f(CW\*(AqX\*(Aq\fR at the beginning of the
1286 string. If you definitely want to match at least one \f(CW\*(AqX\*(Aq\fR, use
1287 \&\f(CW\*(C`X+\*(C'\fR, not \f(CW\*(C`X*\*(C'\fR.
1288 .PP
1289 Sometimes greed is not good. At times, we would like quantifiers to
1290 match a \fIminimal\fR piece of string, rather than a maximal piece. For
1291 this purpose, Larry Wall created the \fIminimal match\fR or
1292 \&\fInon\-greedy\fR quantifiers \f(CW\*(C`??\*(C'\fR, \f(CW\*(C`*?\*(C'\fR, \f(CW\*(C`+?\*(C'\fR, and \f(CW\*(C`{}?\*(C'\fR. These are
1293 the usual quantifiers with a \f(CW\*(Aq?\*(Aq\fR appended to them. They have the
1294 following meanings:
1295 .IP \(bu 4
1296 \&\f(CW\*(C`a??\*(C'\fR means: match \f(CW\*(Aqa\*(Aq\fR 0 or 1 times. Try 0 first, then 1.
1297 .IP \(bu 4
1298 \&\f(CW\*(C`a*?\*(C'\fR means: match \f(CW\*(Aqa\*(Aq\fR 0 or more times, \fIi.e.\fR, any number of times,
1299 but as few times as possible
1300 .IP \(bu 4
1301 \&\f(CW\*(C`a+?\*(C'\fR means: match \f(CW\*(Aqa\*(Aq\fR 1 or more times, \fIi.e.\fR, at least once, but
1302 as few times as possible
1303 .IP \(bu 4
1304 \&\f(CW\*(C`a{n,m}?\*(C'\fR means: match at least \f(CW\*(C`n\*(C'\fR times, not more than \f(CW\*(C`m\*(C'\fR
1305 times, as few times as possible
1306 .IP \(bu 4
1307 \&\f(CW\*(C`a{n,}?\*(C'\fR means: match at least \f(CW\*(C`n\*(C'\fR times, but as few times as
1308 possible
1309 .IP \(bu 4
1310 \&\f(CW\*(C`a{,n}?\*(C'\fR means: match at most \f(CW\*(C`n\*(C'\fR times, but as few times as
1311 possible
1312 .IP \(bu 4
1313 \&\f(CW\*(C`a{n}?\*(C'\fR means: match exactly \f(CW\*(C`n\*(C'\fR times. Because we match exactly
1314 \&\f(CW\*(C`n\*(C'\fR times, \f(CW\*(C`a{n}?\*(C'\fR is equivalent to \f(CW\*(C`a{n}\*(C'\fR and is just there for
1315 notational consistency.
1316 .PP
1317 Let\*(Aqs look at the example above, but with minimal quantifiers:
1318 .PP
1319 .Vb 5
1320 \& $x = "The programming republic of Perl";
1321 \& $x =~ /^(.+?)(e|r)(.*)$/; # matches,
1322 \& # $1 = \*(AqTh\*(Aq
1323 \& # $2 = \*(Aqe\*(Aq
1324 \& # $3 = \*(Aq programming republic of Perl\*(Aq
1325 .Ve
1326 .PP
1327 The minimal string that will allow both the start of the string \f(CW\*(Aq^\*(Aq\fR
1328 and the alternation to match is \f(CW\*(C`Th\*(C'\fR, with the alternation \f(CW\*(C`e|r\*(C'\fR
1329 matching \f(CW\*(Aqe\*(Aq\fR. The second quantifier \f(CW\*(C`.*\*(C'\fR is free to gobble up the
1330 rest of the string.
1331 .PP
1332 .Vb 3
1333 \& $x =~ /(m{1,2}?)(.*?)$/; # matches,
1334 \& # $1 = \*(Aqm\*(Aq
1335 \& # $2 = \*(Aqming republic of Perl\*(Aq
1336 .Ve
1337 .PP
1338 The first string position that this regexp can match is at the first
1339 \&\f(CW\*(Aqm\*(Aq\fR in \f(CW\*(C`programming\*(C'\fR. At this position, the minimal \f(CW\*(C`m{1,2}?\*(C'\fR
1340 matches just one \f(CW\*(Aqm\*(Aq\fR. Although the second quantifier \f(CW\*(C`.*?\*(C'\fR would
1341 prefer to match no characters, it is constrained by the end\-of\-string
1342 anchor \f(CW\*(Aq$\*(Aq\fR to match the rest of the string.
1343 .PP
1344 .Vb 4
1345 \& $x =~ /(.*?)(m{1,2}?)(.*)$/; # matches,
1346 \& # $1 = \*(AqThe progra\*(Aq
1347 \& # $2 = \*(Aqm\*(Aq
1348 \& # $3 = \*(Aqming republic of Perl\*(Aq
1349 .Ve
1350 .PP
1351 In this regexp, you might expect the first minimal quantifier \f(CW\*(C`.*?\*(C'\fR
1352 to match the empty string, because it is not constrained by a \f(CW\*(Aq^\*(Aq\fR
1353 anchor to match the beginning of the word. Principle 0 applies here,
1354 however. Because it is possible for the whole regexp to match at the
1355 start of the string, it \fIwill\fR match at the start of the string. Thus
1356 the first quantifier has to match everything up to the first \f(CW\*(Aqm\*(Aq\fR. The
1357 second minimal quantifier matches just one \f(CW\*(Aqm\*(Aq\fR and the third
1358 quantifier matches the rest of the string.
1359 .PP
1360 .Vb 4
1361 \& $x =~ /(.??)(m{1,2})(.*)$/; # matches,
1362 \& # $1 = \*(Aqa\*(Aq
1363 \& # $2 = \*(Aqmm\*(Aq
1364 \& # $3 = \*(Aqing republic of Perl\*(Aq
1365 .Ve
1366 .PP
1367 Just as in the previous regexp, the first quantifier \f(CW\*(C`.??\*(C'\fR can match
1368 earliest at position \f(CW\*(Aqa\*(Aq\fR, so it does. The second quantifier is
1369 greedy, so it matches \f(CW\*(C`mm\*(C'\fR, and the third matches the rest of the
1370 string.
1371 .PP
1372 We can modify principle 3 above to take into account non\-greedy
1373 quantifiers:
1374 .IP \(bu 4
1375 Principle 3: If there are two or more elements in a regexp, the
1376 leftmost greedy (non\-greedy) quantifier, if any, will match as much
1377 (little) of the string as possible while still allowing the whole
1378 regexp to match. The next leftmost greedy (non\-greedy) quantifier, if
1379 any, will try to match as much (little) of the string remaining
1380 available to it as possible, while still allowing the whole regexp to
1381 match. And so on, until all the regexp elements are satisfied.
1382 .PP
1383 Just like alternation, quantifiers are also susceptible to
1384 backtracking. Here is a step\-by\-step analysis of the example
1385 .PP
1386 .Vb 5
1387 \& $x = "the cat in the hat";
1388 \& $x =~ /^(.*)(at)(.*)$/; # matches,
1389 \& # $1 = \*(Aqthe cat in the h\*(Aq
1390 \& # $2 = \*(Aqat\*(Aq
1391 \& # $3 = \*(Aq\*(Aq (0 matches)
1392 .Ve
1393 .IP 1. 4
1394 Start with the first letter in the string \f(CW\*(Aqt\*(Aq\fR.
1395 .IP 2. 4
1396 The first quantifier \f(CW\*(Aq.*\*(Aq\fR starts out by matching the whole
1397 string \f(CW"the cat in the hat"\fR.
1398 .IP 3. 4
1399 \&\f(CW\*(Aqa\*(Aq\fR in the regexp element \f(CW\*(Aqat\*(Aq\fR doesn\*(Aqt match the end
1400 of the string. Backtrack one character.
1401 .IP 4. 4
1402 \&\f(CW\*(Aqa\*(Aq\fR in the regexp element \f(CW\*(Aqat\*(Aq\fR still doesn\*(Aqt match
1403 the last letter of the string \f(CW\*(Aqt\*(Aq\fR, so backtrack one more character.
1404 .IP 5. 4
1405 Now we can match the \f(CW\*(Aqa\*(Aq\fR and the \f(CW\*(Aqt\*(Aq\fR.
1406 .IP 6. 4
1407 Move on to the third element \f(CW\*(Aq.*\*(Aq\fR. Since we are at the
1408 end of the string and \f(CW\*(Aq.*\*(Aq\fR can match 0 times, assign it the empty
1409 string.
1410 .IP 7. 4
1411 We are done!
1412 .PP
1413 Most of the time, all this moving forward and backtracking happens
1414 quickly and searching is fast. There are some pathological regexps,
1415 however, whose execution time exponentially grows with the size of the
1416 string. A typical structure that blows up in your face is of the form
1417 .PP
1418 .Vb 1
1419 \& /(a|b+)*/;
1420 .Ve
1421 .PP
1422 The problem is the nested indeterminate quantifiers. There are many
1423 different ways of partitioning a string of length n between the \f(CW\*(Aq+\*(Aq\fR
1424 and \f(CW\*(Aq*\*(Aq\fR: one repetition with \f(CW\*(C`b+\*(C'\fR of length n, two repetitions with
1425 the first \f(CW\*(C`b+\*(C'\fR length k and the second with length n\-k, m repetitions
1426 whose bits add up to length n, \fIetc\fR. In fact there are an exponential
1427 number of ways to partition a string as a function of its length. A
1428 regexp may get lucky and match early in the process, but if there is
1429 no match, Perl will try \fIevery\fR possibility before giving up. So be
1430 careful with nested \f(CW\*(Aq*\*(Aq\fR\*(Aqs, \f(CW\*(C`{n,m}\*(C'\fR\*(Aqs, and \f(CW\*(Aq+\*(Aq\fR\*(Aqs. The book
1431 \&\fIMastering Regular Expressions\fR by Jeffrey Friedl gives a wonderful
1432 discussion of this and other efficiency issues.
1433 .SS "Possessive quantifiers"
1434 .IX Subsection "Possessive quantifiers"
1435 Backtracking during the relentless search for a match may be a waste
1436 of time, particularly when the match is bound to fail. Consider
1437 the simple pattern
1438 .PP
1439 .Vb 1
1440 \& /^\ew+\es+\ew+$/; # a word, spaces, a word
1441 .Ve
1442 .PP
1443 Whenever this is applied to a string which doesn\*(Aqt quite meet the
1444 pattern\*(Aqs expectations such as \f(CW"abc\ \ "\fR or \f(CW"abc\ \ def\ "\fR,
1445 the regexp engine will backtrack, approximately once for each character
1446 in the string. But we know that there is no way around taking \fIall\fR
1447 of the initial word characters to match the first repetition, that \fIall\fR
1448 spaces must be eaten by the middle part, and the same goes for the second
1449 word.
1450 .PP
1451 With the introduction of the \fIpossessive quantifiers\fR in Perl 5.10, we
1452 have a way of instructing the regexp engine not to backtrack, with the
1453 usual quantifiers with a \f(CW\*(Aq+\*(Aq\fR appended to them. This makes them greedy as
1454 well as stingy; once they succeed they won\*(Aqt give anything back to permit
1455 another solution. They have the following meanings:
1456 .IP \(bu 4
1457 \&\f(CW\*(C`a{n,m}+\*(C'\fR means: match at least \f(CW\*(C`n\*(C'\fR times, not more than \f(CW\*(C`m\*(C'\fR times,
1458 as many times as possible, and don\*(Aqt give anything up. \f(CW\*(C`a?+\*(C'\fR is short
1459 for \f(CW\*(C`a{0,1}+\*(C'\fR
1460 .IP \(bu 4
1461 \&\f(CW\*(C`a{n,}+\*(C'\fR means: match at least \f(CW\*(C`n\*(C'\fR times, but as many times as possible,
1462 and don\*(Aqt give anything up. \f(CW\*(C`a++\*(C'\fR is short for \f(CW\*(C`a{1,}+\*(C'\fR.
1463 .IP \(bu 4
1464 \&\f(CW\*(C`a{,n}+\*(C'\fR means: match as many times as possible up to at most \f(CW\*(C`n\*(C'\fR
1465 times, and don\*(Aqt give anything up. \f(CW\*(C`a*+\*(C'\fR is short for \f(CW\*(C`a{0,}+\*(C'\fR.
1466 .IP \(bu 4
1467 \&\f(CW\*(C`a{n}+\*(C'\fR means: match exactly \f(CW\*(C`n\*(C'\fR times. It is just there for
1468 notational consistency.
1469 .PP
1470 These possessive quantifiers represent a special case of a more general
1471 concept, the \fIindependent subexpression\fR, see below.
1472 .PP
1473 As an example where a possessive quantifier is suitable we consider
1474 matching a quoted string, as it appears in several programming languages.
1475 The backslash is used as an escape character that indicates that the
1476 next character is to be taken literally, as another character for the
1477 string. Therefore, after the opening quote, we expect a (possibly
1478 empty) sequence of alternatives: either some character except an
1479 unescaped quote or backslash or an escaped character.
1480 .PP
1481 .Vb 1
1482 \& /"(?:[^"\e\e]++|\e\e.)*+"/;
1483 .Ve
1484 .SS "Building a regexp"
1485 .IX Subsection "Building a regexp"
1486 At this point, we have all the basic regexp concepts covered, so let\*(Aqs
1487 give a more involved example of a regular expression. We will build a
1488 regexp that matches numbers.
1489 .PP
1490 The first task in building a regexp is to decide what we want to match
1491 and what we want to exclude. In our case, we want to match both
1492 integers and floating point numbers and we want to reject any string
1493 that isn\*(Aqt a number.
1494 .PP
1495 The next task is to break the problem down into smaller problems that
1496 are easily converted into a regexp.
1497 .PP
1498 The simplest case is integers. These consist of a sequence of digits,
1499 with an optional sign in front. The digits we can represent with
1500 \&\f(CW\*(C`\ed+\*(C'\fR and the sign can be matched with \f(CW\*(C`[+\-]\*(C'\fR. Thus the integer
1501 regexp is
1502 .PP
1503 .Vb 1
1504 \& /[+\-]?\ed+/; # matches integers
1505 .Ve
1506 .PP
1507 A floating point number potentially has a sign, an integral part, a
1508 decimal point, a fractional part, and an exponent. One or more of these
1509 parts is optional, so we need to check out the different
1510 possibilities. Floating point numbers which are in proper form include
1511 123., 0.345, .34, \-1e6, and 25.4E\-72. As with integers, the sign out
1512 front is completely optional and can be matched by \f(CW\*(C`[+\-]?\*(C'\fR. We can
1513 see that if there is no exponent, floating point numbers must have a
1514 decimal point, otherwise they are integers. We might be tempted to
1515 model these with \f(CW\*(C`\ed*\e.\ed*\*(C'\fR, but this would also match just a single
1516 decimal point, which is not a number. So the three cases of floating
1517 point number without exponent are
1518 .PP
1519 .Vb 3
1520 \& /[+\-]?\ed+\e./; # 1., 321., etc.
1521 \& /[+\-]?\e.\ed+/; # .1, .234, etc.
1522 \& /[+\-]?\ed+\e.\ed+/; # 1.0, 30.56, etc.
1523 .Ve
1524 .PP
1525 These can be combined into a single regexp with a three\-way alternation:
1526 .PP
1527 .Vb 1
1528 \& /[+\-]?(\ed+\e.\ed+|\ed+\e.|\e.\ed+)/; # floating point, no exponent
1529 .Ve
1530 .PP
1531 In this alternation, it is important to put \f(CW\*(Aq\ed+\e.\ed+\*(Aq\fR before
1532 \&\f(CW\*(Aq\ed+\e.\*(Aq\fR. If \f(CW\*(Aq\ed+\e.\*(Aq\fR were first, the regexp would happily match that
1533 and ignore the fractional part of the number.
1534 .PP
1535 Now consider floating point numbers with exponents. The key
1536 observation here is that \fIboth\fR integers and numbers with decimal
1537 points are allowed in front of an exponent. Then exponents, like the
1538 overall sign, are independent of whether we are matching numbers with
1539 or without decimal points, and can be "decoupled" from the
1540 mantissa. The overall form of the regexp now becomes clear:
1541 .PP
1542 .Vb 1
1543 \& /^(optional sign)(integer | f.p. mantissa)(optional exponent)$/;
1544 .Ve
1545 .PP
1546 The exponent is an \f(CW\*(Aqe\*(Aq\fR or \f(CW\*(AqE\*(Aq\fR, followed by an integer. So the
1547 exponent regexp is
1548 .PP
1549 .Vb 1
1550 \& /[eE][+\-]?\ed+/; # exponent
1551 .Ve
1552 .PP
1553 Putting all the parts together, we get a regexp that matches numbers:
1554 .PP
1555 .Vb 1
1556 \& /^[+\-]?(\ed+\e.\ed+|\ed+\e.|\e.\ed+|\ed+)([eE][+\-]?\ed+)?$/; # Ta da!
1557 .Ve
1558 .PP
1559 Long regexps like this may impress your friends, but can be hard to
1560 decipher. In complex situations like this, the \f(CW\*(C`/x\*(C'\fR modifier for a
1561 match is invaluable. It allows one to put nearly arbitrary whitespace
1562 and comments into a regexp without affecting their meaning. Using it,
1563 we can rewrite our "extended" regexp in the more pleasing form
1564 .PP
1565 .Vb 10
1566 \& /^
1567 \& [+\-]? # first, match an optional sign
1568 \& ( # then match integers or f.p. mantissas:
1569 \& \ed+\e.\ed+ # mantissa of the form a.b
1570 \& |\ed+\e. # mantissa of the form a.
1571 \& |\e.\ed+ # mantissa of the form .b
1572 \& |\ed+ # integer of the form a
1573 \& )
1574 \& ( [eE] [+\-]? \ed+ )? # finally, optionally match an exponent
1575 \& $/x;
1576 .Ve
1577 .PP
1578 If whitespace is mostly irrelevant, how does one include space
1579 characters in an extended regexp? The answer is to backslash it
1580 \&\f(CW\*(Aq\e\ \*(Aq\fR or put it in a character class \f(CW\*(C`[\ ]\*(C'\fR. The same thing
1581 goes for pound signs: use \f(CW\*(C`\e#\*(C'\fR or \f(CW\*(C`[#]\*(C'\fR. For instance, Perl allows
1582 a space between the sign and the mantissa or integer, and we could add
1583 this to our regexp as follows:
1584 .PP
1585 .Vb 10
1586 \& /^
1587 \& [+\-]?\e * # first, match an optional sign *and space*
1588 \& ( # then match integers or f.p. mantissas:
1589 \& \ed+\e.\ed+ # mantissa of the form a.b
1590 \& |\ed+\e. # mantissa of the form a.
1591 \& |\e.\ed+ # mantissa of the form .b
1592 \& |\ed+ # integer of the form a
1593 \& )
1594 \& ( [eE] [+\-]? \ed+ )? # finally, optionally match an exponent
1595 \& $/x;
1596 .Ve
1597 .PP
1598 In this form, it is easier to see a way to simplify the
1599 alternation. Alternatives 1, 2, and 4 all start with \f(CW\*(C`\ed+\*(C'\fR, so it
1600 could be factored out:
1601 .PP
1602 .Vb 11
1603 \& /^
1604 \& [+\-]?\e * # first, match an optional sign
1605 \& ( # then match integers or f.p. mantissas:
1606 \& \ed+ # start out with a ...
1607 \& (
1608 \& \e.\ed* # mantissa of the form a.b or a.
1609 \& )? # ? takes care of integers of the form a
1610 \& |\e.\ed+ # mantissa of the form .b
1611 \& )
1612 \& ( [eE] [+\-]? \ed+ )? # finally, optionally match an exponent
1613 \& $/x;
1614 .Ve
1615 .PP
1616 Starting in Perl v5.26, specifying \f(CW\*(C`/xx\*(C'\fR changes the square\-bracketed
1617 portions of a pattern to ignore tabs and space characters unless they
1618 are escaped by preceding them with a backslash. So, we could write
1619 .PP
1620 .Vb 11
1621 \& /^
1622 \& [ + \- ]?\e * # first, match an optional sign
1623 \& ( # then match integers or f.p. mantissas:
1624 \& \ed+ # start out with a ...
1625 \& (
1626 \& \e.\ed* # mantissa of the form a.b or a.
1627 \& )? # ? takes care of integers of the form a
1628 \& |\e.\ed+ # mantissa of the form .b
1629 \& )
1630 \& ( [ e E ] [ + \- ]? \ed+ )? # finally, optionally match an exponent
1631 \& $/xx;
1632 .Ve
1633 .PP
1634 This doesn\*(Aqt really improve the legibility of this example, but it\*(Aqs
1635 available in case you want it. Squashing the pattern down to the
1636 compact form, we have
1637 .PP
1638 .Vb 1
1639 \& /^[+\-]?\e *(\ed+(\e.\ed*)?|\e.\ed+)([eE][+\-]?\ed+)?$/;
1640 .Ve
1641 .PP
1642 This is our final regexp. To recap, we built a regexp by
1643 .IP \(bu 4
1644 specifying the task in detail,
1645 .IP \(bu 4
1646 breaking down the problem into smaller parts,
1647 .IP \(bu 4
1648 translating the small parts into regexps,
1649 .IP \(bu 4
1650 combining the regexps,
1651 .IP \(bu 4
1652 and optimizing the final combined regexp.
1653 .PP
1654 These are also the typical steps involved in writing a computer
1655 program. This makes perfect sense, because regular expressions are
1656 essentially programs written in a little computer language that specifies
1657 patterns.
1658 .SS "Using regular expressions in Perl"
1659 .IX Subsection "Using regular expressions in Perl"
1660 The last topic of Part 1 briefly covers how regexps are used in Perl
1661 programs. Where do they fit into Perl syntax?
1662 .PP
1663 We have already introduced the matching operator in its default
1664 \&\f(CW\*(C`/regexp/\*(C'\fR and arbitrary delimiter \f(CW\*(C`m!regexp!\*(C'\fR forms. We have used
1665 the binding operator \f(CW\*(C`=~\*(C'\fR and its negation \f(CW\*(C`!~\*(C'\fR to test for string
1666 matches. Associated with the matching operator, we have discussed the
1667 single line \f(CW\*(C`/s\*(C'\fR, multi\-line \f(CW\*(C`/m\*(C'\fR, case\-insensitive \f(CW\*(C`/i\*(C'\fR and
1668 extended \f(CW\*(C`/x\*(C'\fR modifiers. There are a few more things you might
1669 want to know about matching operators.
1670 .PP
1671 \fIProhibiting substitution\fR
1672 .IX Subsection "Prohibiting substitution"
1673 .PP
1674 If you change \f(CW$pattern\fR after the first substitution happens, Perl
1675 will ignore it. If you don\*(Aqt want any substitutions at all, use the
1676 special delimiter \f(CW\*(C`m\*(Aq\*(Aq\*(C'\fR:
1677 .PP
1678 .Vb 4
1679 \& @pattern = (\*(AqSeuss\*(Aq);
1680 \& while (<>) {
1681 \& print if m\*(Aq@pattern\*(Aq; # matches literal \*(Aq@pattern\*(Aq, not \*(AqSeuss\*(Aq
1682 \& }
1683 .Ve
1684 .PP
1685 Similar to strings, \f(CW\*(C`m\*(Aq\*(Aq\*(C'\fR acts like apostrophes on a regexp; all other
1686 \&\f(CW\*(Aqm\*(Aq\fR delimiters act like quotes. If the regexp evaluates to the empty string,
1687 the regexp in the \fIlast successful match\fR is used instead. So we have
1688 .PP
1689 .Vb 2
1690 \& "dog" =~ /d/; # \*(Aqd\*(Aq matches
1691 \& "dogbert" =~ //; # this matches the \*(Aqd\*(Aq regexp used before
1692 .Ve
1693 .PP
1694 \fIGlobal matching\fR
1695 .IX Subsection "Global matching"
1696 .PP
1697 The final two modifiers we will discuss here,
1698 \&\f(CW\*(C`/g\*(C'\fR and \f(CW\*(C`/c\*(C'\fR, concern multiple matches.
1699 The modifier \f(CW\*(C`/g\*(C'\fR stands for global matching and allows the
1700 matching operator to match within a string as many times as possible.
1701 In scalar context, successive invocations against a string will have
1702 \&\f(CW\*(C`/g\*(C'\fR jump from match to match, keeping track of position in the
1703 string as it goes along. You can get or set the position with the
1704 \&\f(CWpos()\fR function.
1705 .PP
1706 The use of \f(CW\*(C`/g\*(C'\fR is shown in the following example. Suppose we have
1707 a string that consists of words separated by spaces. If we know how
1708 many words there are in advance, we could extract the words using
1709 groupings:
1710 .PP
1711 .Vb 5
1712 \& $x = "cat dog house"; # 3 words
1713 \& $x =~ /^\es*(\ew+)\es+(\ew+)\es+(\ew+)\es*$/; # matches,
1714 \& # $1 = \*(Aqcat\*(Aq
1715 \& # $2 = \*(Aqdog\*(Aq
1716 \& # $3 = \*(Aqhouse\*(Aq
1717 .Ve
1718 .PP
1719 But what if we had an indeterminate number of words? This is the sort
1720 of task \f(CW\*(C`/g\*(C'\fR was made for. To extract all words, form the simple
1721 regexp \f(CW\*(C`(\ew+)\*(C'\fR and loop over all matches with \f(CW\*(C`/(\ew+)/g\*(C'\fR:
1722 .PP
1723 .Vb 3
1724 \& while ($x =~ /(\ew+)/g) {
1725 \& print "Word is $1, ends at position ", pos $x, "\en";
1726 \& }
1727 .Ve
1728 .PP
1729 prints
1730 .PP
1731 .Vb 3
1732 \& Word is cat, ends at position 3
1733 \& Word is dog, ends at position 7
1734 \& Word is house, ends at position 13
1735 .Ve
1736 .PP
1737 A failed match or changing the target string resets the position. If
1738 you don\*(Aqt want the position reset after failure to match, add the
1739 \&\f(CW\*(C`/c\*(C'\fR, as in \f(CW\*(C`/regexp/gc\*(C'\fR. The current position in the string is
1740 associated with the string, not the regexp. This means that different
1741 strings have different positions and their respective positions can be
1742 set or read independently.
1743 .PP
1744 In list context, \f(CW\*(C`/g\*(C'\fR returns a list of matched groupings, or if
1745 there are no groupings, a list of matches to the whole regexp. So if
1746 we wanted just the words, we could use
1747 .PP
1748 .Vb 4
1749 \& @words = ($x =~ /(\ew+)/g); # matches,
1750 \& # $words[0] = \*(Aqcat\*(Aq
1751 \& # $words[1] = \*(Aqdog\*(Aq
1752 \& # $words[2] = \*(Aqhouse\*(Aq
1753 .Ve
1754 .PP
1755 Closely associated with the \f(CW\*(C`/g\*(C'\fR modifier is the \f(CW\*(C`\eG\*(C'\fR anchor. The
1756 \&\f(CW\*(C`\eG\*(C'\fR anchor matches at the point where the previous \f(CW\*(C`/g\*(C'\fR match left
1757 off. \f(CW\*(C`\eG\*(C'\fR allows us to easily do context\-sensitive matching:
1758 .PP
1759 .Vb 12
1760 \& $metric = 1; # use metric units
1761 \& ...
1762 \& $x = <FILE>; # read in measurement
1763 \& $x =~ /^([+\-]?\ed+)\es*/g; # get magnitude
1764 \& $weight = $1;
1765 \& if ($metric) { # error checking
1766 \& print "Units error!" unless $x =~ /\eGkg\e./g;
1767 \& }
1768 \& else {
1769 \& print "Units error!" unless $x =~ /\eGlbs\e./g;
1770 \& }
1771 \& $x =~ /\eG\es+(widget|sprocket)/g; # continue processing
1772 .Ve
1773 .PP
1774 The combination of \f(CW\*(C`/g\*(C'\fR and \f(CW\*(C`\eG\*(C'\fR allows us to process the string a
1775 bit at a time and use arbitrary Perl logic to decide what to do next.
1776 .PP
1777 \&\f(CW\*(C`\eG\*(C'\fR is also invaluable in processing fixed\-length records with
1778 regexps. Suppose we have a snippet of coding region DNA, encoded as
1779 base pair letters \f(CW\*(C`ATCGTTGAAT...\*(C'\fR and we want to find all the stop
1780 codons \f(CW\*(C`TGA\*(C'\fR. In a coding region, codons are 3\-letter sequences, so
1781 we can think of the DNA snippet as a sequence of 3\-letter records. The
1782 naive regexp
1783 .PP
1784 .Vb 3
1785 \& # expanded, this is "ATC GTT GAA TGC AAA TGA CAT GAC"
1786 \& $dna = "ATCGTTGAATGCAAATGACATGAC";
1787 \& $dna =~ /TGA/;
1788 .Ve
1789 .PP
1790 doesn\*(Aqt work; it may match a \f(CW\*(C`TGA\*(C'\fR, but there is no guarantee that
1791 the match is aligned with codon boundaries, \fIe.g.\fR, the substring
1792 \&\f(CW\*(C`GTT\ GAA\*(C'\fR gives a match. A better solution is
1793 .PP
1794 .Vb 3
1795 \& while ($dna =~ /(\ew\ew\ew)*?TGA/g) { # note the minimal *?
1796 \& print "Got a TGA stop codon at position ", pos $dna, "\en";
1797 \& }
1798 .Ve
1799 .PP
1800 which prints
1801 .PP
1802 .Vb 2
1803 \& Got a TGA stop codon at position 18
1804 \& Got a TGA stop codon at position 23
1805 .Ve
1806 .PP
1807 Position 18 is good, but position 23 is bogus. What happened?
1808 .PP
1809 The answer is that our regexp works well until we get past the last
1810 real match. Then the regexp will fail to match a synchronized \f(CW\*(C`TGA\*(C'\fR
1811 and start stepping ahead one character position at a time, not what we
1812 want. The solution is to use \f(CW\*(C`\eG\*(C'\fR to anchor the match to the codon
1813 alignment:
1814 .PP
1815 .Vb 3
1816 \& while ($dna =~ /\eG(\ew\ew\ew)*?TGA/g) {
1817 \& print "Got a TGA stop codon at position ", pos $dna, "\en";
1818 \& }
1819 .Ve
1820 .PP
1821 This prints
1822 .PP
1823 .Vb 1
1824 \& Got a TGA stop codon at position 18
1825 .Ve
1826 .PP
1827 which is the correct answer. This example illustrates that it is
1828 important not only to match what is desired, but to reject what is not
1829 desired.
1830 .PP
1831 (There are other regexp modifiers that are available, such as
1832 \&\f(CW\*(C`/o\*(C'\fR, but their specialized uses are beyond the
1833 scope of this introduction. )
1834 .PP
1835 \fISearch and replace\fR
1836 .IX Subsection "Search and replace"
1837 .PP
1838 Regular expressions also play a big role in \fIsearch and replace\fR
1839 operations in Perl. Search and replace is accomplished with the
1840 \&\f(CW\*(C`s///\*(C'\fR operator. The general form is
1841 \&\f(CW\*(C`s/regexp/replacement/modifiers\*(C'\fR, with everything we know about
1842 regexps and modifiers applying in this case as well. The
1843 \&\fIreplacement\fR is a Perl double\-quoted string that replaces in the
1844 string whatever is matched with the \f(CW\*(C`regexp\*(C'\fR. The operator \f(CW\*(C`=~\*(C'\fR is
1845 also used here to associate a string with \f(CW\*(C`s///\*(C'\fR. If matching
1846 against \f(CW$_\fR, the \f(CW\*(C`$_\ =~\*(C'\fR can be dropped. If there is a match,
1847 \&\f(CW\*(C`s///\*(C'\fR returns the number of substitutions made; otherwise it returns
1848 false. Here are a few examples:
1849 .PP
1850 .Vb 8
1851 \& $x = "Time to feed the cat!";
1852 \& $x =~ s/cat/hacker/; # $x contains "Time to feed the hacker!"
1853 \& if ($x =~ s/^(Time.*hacker)!$/$1 now!/) {
1854 \& $more_insistent = 1;
1855 \& }
1856 \& $y = "\*(Aqquoted words\*(Aq";
1857 \& $y =~ s/^\*(Aq(.*)\*(Aq$/$1/; # strip single quotes,
1858 \& # $y contains "quoted words"
1859 .Ve
1860 .PP
1861 In the last example, the whole string was matched, but only the part
1862 inside the single quotes was grouped. With the \f(CW\*(C`s///\*(C'\fR operator, the
1863 matched variables \f(CW$1\fR, \f(CW$2\fR, \fIetc\fR. are immediately available for use
1864 in the replacement expression, so we use \f(CW$1\fR to replace the quoted
1865 string with just what was quoted. With the global modifier, \f(CW\*(C`s///g\*(C'\fR
1866 will search and replace all occurrences of the regexp in the string:
1867 .PP
1868 .Vb 6
1869 \& $x = "I batted 4 for 4";
1870 \& $x =~ s/4/four/; # doesn\*(Aqt do it all:
1871 \& # $x contains "I batted four for 4"
1872 \& $x = "I batted 4 for 4";
1873 \& $x =~ s/4/four/g; # does it all:
1874 \& # $x contains "I batted four for four"
1875 .Ve
1876 .PP
1877 If you prefer "regex" over "regexp" in this tutorial, you could use
1878 the following program to replace it:
1879 .PP
1880 .Vb 9
1881 \& % cat > simple_replace
1882 \& #!/usr/bin/perl
1883 \& $regexp = shift;
1884 \& $replacement = shift;
1885 \& while (<>) {
1886 \& s/$regexp/$replacement/g;
1887 \& print;
1888 \& }
1889 \& ^D
1890 \&
1891 \& % simple_replace regexp regex perlretut.pod
1892 .Ve
1893 .PP
1894 In \f(CW\*(C`simple_replace\*(C'\fR we used the \f(CW\*(C`s///g\*(C'\fR modifier to replace all
1895 occurrences of the regexp on each line. (Even though the regular
1896 expression appears in a loop, Perl is smart enough to compile it
1897 only once.) As with \f(CW\*(C`simple_grep\*(C'\fR, both the
1898 \&\f(CW\*(C`print\*(C'\fR and the \f(CW\*(C`s/$regexp/$replacement/g\*(C'\fR use \f(CW$_\fR implicitly.
1899 .PP
1900 If you don\*(Aqt want \f(CW\*(C`s///\*(C'\fR to change your original variable you can use
1901 the non\-destructive substitute modifier, \f(CW\*(C`s///r\*(C'\fR. This changes the
1902 behavior so that \f(CW\*(C`s///r\*(C'\fR returns the final substituted string
1903 (instead of the number of substitutions):
1904 .PP
1905 .Vb 3
1906 \& $x = "I like dogs.";
1907 \& $y = $x =~ s/dogs/cats/r;
1908 \& print "$x $y\en";
1909 .Ve
1910 .PP
1911 That example will print "I like dogs. I like cats". Notice the original
1912 \&\f(CW$x\fR variable has not been affected. The overall
1913 result of the substitution is instead stored in \f(CW$y\fR. If the
1914 substitution doesn\*(Aqt affect anything then the original string is
1915 returned:
1916 .PP
1917 .Vb 3
1918 \& $x = "I like dogs.";
1919 \& $y = $x =~ s/elephants/cougars/r;
1920 \& print "$x $y\en"; # prints "I like dogs. I like dogs."
1921 .Ve
1922 .PP
1923 One other interesting thing that the \f(CW\*(C`s///r\*(C'\fR flag allows is chaining
1924 substitutions:
1925 .PP
1926 .Vb 4
1927 \& $x = "Cats are great.";
1928 \& print $x =~ s/Cats/Dogs/r =~ s/Dogs/Frogs/r =~
1929 \& s/Frogs/Hedgehogs/r, "\en";
1930 \& # prints "Hedgehogs are great."
1931 .Ve
1932 .PP
1933 A modifier available specifically to search and replace is the
1934 \&\f(CW\*(C`s///e\*(C'\fR evaluation modifier. \f(CW\*(C`s///e\*(C'\fR treats the
1935 replacement text as Perl code, rather than a double\-quoted
1936 string. The value that the code returns is substituted for the
1937 matched substring. \f(CW\*(C`s///e\*(C'\fR is useful if you need to do a bit of
1938 computation in the process of replacing text. This example counts
1939 character frequencies in a line:
1940 .PP
1941 .Vb 4
1942 \& $x = "Bill the cat";
1943 \& $x =~ s/(.)/$chars{$1}++;$1/eg; # final $1 replaces char with itself
1944 \& print "frequency of \*(Aq$_\*(Aq is $chars{$_}\en"
1945 \& foreach (sort {$chars{$b} <=> $chars{$a}} keys %chars);
1946 .Ve
1947 .PP
1948 This prints
1949 .PP
1950 .Vb 9
1951 \& frequency of \*(Aq \*(Aq is 2
1952 \& frequency of \*(Aqt\*(Aq is 2
1953 \& frequency of \*(Aql\*(Aq is 2
1954 \& frequency of \*(AqB\*(Aq is 1
1955 \& frequency of \*(Aqc\*(Aq is 1
1956 \& frequency of \*(Aqe\*(Aq is 1
1957 \& frequency of \*(Aqh\*(Aq is 1
1958 \& frequency of \*(Aqi\*(Aq is 1
1959 \& frequency of \*(Aqa\*(Aq is 1
1960 .Ve
1961 .PP
1962 As with the match \f(CW\*(C`m//\*(C'\fR operator, \f(CW\*(C`s///\*(C'\fR can use other delimiters,
1963 such as \f(CW\*(C`s!!!\*(C'\fR and \f(CW\*(C`s{}{}\*(C'\fR, and even \f(CW\*(C`s{}//\*(C'\fR. If single quotes are
1964 used \f(CW\*(C`s\*(Aq\*(Aq\*(Aq\*(C'\fR, then the regexp and replacement are
1965 treated as single\-quoted strings and there are no
1966 variable substitutions. \f(CW\*(C`s///\*(C'\fR in list context
1967 returns the same thing as in scalar context, \fIi.e.\fR, the number of
1968 matches.
1969 .PP
1970 \fIThe split function\fR
1971 .IX Subsection "The split function"
1972 .PP
1973 The \f(CWsplit()\fR function is another place where a regexp is used.
1974 \&\f(CW\*(C`split /regexp/, string, limit\*(C'\fR separates the \f(CW\*(C`string\*(C'\fR operand into
1975 a list of substrings and returns that list. The regexp must be designed
1976 to match whatever constitutes the separators for the desired substrings.
1977 The \f(CW\*(C`limit\*(C'\fR, if present, constrains splitting into no more than \f(CW\*(C`limit\*(C'\fR
1978 number of strings. For example, to split a string into words, use
1979 .PP
1980 .Vb 4
1981 \& $x = "Calvin and Hobbes";
1982 \& @words = split /\es+/, $x; # $word[0] = \*(AqCalvin\*(Aq
1983 \& # $word[1] = \*(Aqand\*(Aq
1984 \& # $word[2] = \*(AqHobbes\*(Aq
1985 .Ve
1986 .PP
1987 If the empty regexp \f(CW\*(C`//\*(C'\fR is used, the regexp always matches and
1988 the string is split into individual characters. If the regexp has
1989 groupings, then the resulting list contains the matched substrings from the
1990 groupings as well. For instance,
1991 .PP
1992 .Vb 12
1993 \& $x = "/usr/bin/perl";
1994 \& @dirs = split m!/!, $x; # $dirs[0] = \*(Aq\*(Aq
1995 \& # $dirs[1] = \*(Aqusr\*(Aq
1996 \& # $dirs[2] = \*(Aqbin\*(Aq
1997 \& # $dirs[3] = \*(Aqperl\*(Aq
1998 \& @parts = split m!(/)!, $x; # $parts[0] = \*(Aq\*(Aq
1999 \& # $parts[1] = \*(Aq/\*(Aq
2000 \& # $parts[2] = \*(Aqusr\*(Aq
2001 \& # $parts[3] = \*(Aq/\*(Aq
2002 \& # $parts[4] = \*(Aqbin\*(Aq
2003 \& # $parts[5] = \*(Aq/\*(Aq
2004 \& # $parts[6] = \*(Aqperl\*(Aq
2005 .Ve
2006 .PP
2007 Since the first character of \f(CW$x\fR matched the regexp, \f(CW\*(C`split\*(C'\fR prepended
2008 an empty initial element to the list.
2009 .PP
2010 If you have read this far, congratulations! You now have all the basic
2011 tools needed to use regular expressions to solve a wide range of text
2012 processing problems. If this is your first time through the tutorial,
2013 why not stop here and play around with regexps a while.... Part\ 2
2014 concerns the more esoteric aspects of regular expressions and those
2015 concepts certainly aren\*(Aqt needed right at the start.
2016 .SH "Part 2: Power tools"
2017 .IX Header "Part 2: Power tools"
2018 OK, you know the basics of regexps and you want to know more. If
2019 matching regular expressions is analogous to a walk in the woods, then
2020 the tools discussed in Part 1 are analogous to topo maps and a
2021 compass, basic tools we use all the time. Most of the tools in part 2
2022 are analogous to flare guns and satellite phones. They aren\*(Aqt used
2023 too often on a hike, but when we are stuck, they can be invaluable.
2024 .PP
2025 What follows are the more advanced, less used, or sometimes esoteric
2026 capabilities of Perl regexps. In Part 2, we will assume you are
2027 comfortable with the basics and concentrate on the advanced features.
2028 .SS "More on characters, strings, and character classes"
2029 .IX Subsection "More on characters, strings, and character classes"
2030 There are a number of escape sequences and character classes that we
2031 haven\*(Aqt covered yet.
2032 .PP
2033 There are several escape sequences that convert characters or strings
2034 between upper and lower case, and they are also available within
2035 patterns. \f(CW\*(C`\el\*(C'\fR and \f(CW\*(C`\eu\*(C'\fR convert the next character to lower or
2036 upper case, respectively:
2037 .PP
2038 .Vb 4
2039 \& $x = "perl";
2040 \& $string =~ /\eu$x/; # matches \*(AqPerl\*(Aq in $string
2041 \& $x = "M(rs?|s)\e\e."; # note the double backslash
2042 \& $string =~ /\el$x/; # matches \*(Aqmr.\*(Aq, \*(Aqmrs.\*(Aq, and \*(Aqms.\*(Aq,
2043 .Ve
2044 .PP
2045 A \f(CW\*(C`\eL\*(C'\fR or \f(CW\*(C`\eU\*(C'\fR indicates a lasting conversion of case, until
2046 terminated by \f(CW\*(C`\eE\*(C'\fR or thrown over by another \f(CW\*(C`\eU\*(C'\fR or \f(CW\*(C`\eL\*(C'\fR:
2047 .PP
2048 .Vb 4
2049 \& $x = "This word is in lower case:\eL SHOUT\eE";
2050 \& $x =~ /shout/; # matches
2051 \& $x = "I STILL KEYPUNCH CARDS FOR MY 360";
2052 \& $x =~ /\eUkeypunch/; # matches punch card string
2053 .Ve
2054 .PP
2055 If there is no \f(CW\*(C`\eE\*(C'\fR, case is converted until the end of the
2056 string. The regexps \f(CW\*(C`\eL\eu$word\*(C'\fR or \f(CW\*(C`\eu\eL$word\*(C'\fR convert the first
2057 character of \f(CW$word\fR to uppercase and the rest of the characters to
2058 lowercase. (Beyond ASCII characters, it gets somewhat more complicated;
2059 \&\f(CW\*(C`\eu\*(C'\fR actually performs \fItitlecase\fR mapping, which for most characters
2060 is the same as uppercase, but not for all; see
2061 <https://unicode.org/faq/casemap_charprop.html#4>.)
2062 .PP
2063 Control characters can be escaped with \f(CW\*(C`\ec\*(C'\fR, so that a control\-Z
2064 character would be matched with \f(CW\*(C`\ecZ\*(C'\fR. The escape sequence
2065 \&\f(CW\*(C`\eQ\*(C'\fR...\f(CW\*(C`\eE\*(C'\fR quotes, or protects most non\-alphabetic characters. For
2066 instance,
2067 .PP
2068 .Vb 2
2069 \& $x = "\eQThat !^*&%~& cat!";
2070 \& $x =~ /\eQ!^*&%~&\eE/; # check for rough language
2071 .Ve
2072 .PP
2073 It does not protect \f(CW\*(Aq$\*(Aq\fR or \f(CW\*(Aq@\*(Aq\fR, so that variables can still be
2074 substituted.
2075 .PP
2076 \&\f(CW\*(C`\eQ\*(C'\fR, \f(CW\*(C`\eL\*(C'\fR, \f(CW\*(C`\el\*(C'\fR, \f(CW\*(C`\eU\*(C'\fR, \f(CW\*(C`\eu\*(C'\fR and \f(CW\*(C`\eE\*(C'\fR are actually part of
2077 double\-quotish syntax, and not part of regexp syntax proper. They will
2078 work if they appear in a regular expression embedded directly in a
2079 program, but not when contained in a string that is interpolated in a
2080 pattern.
2081 .PP
2082 Perl regexps can handle more than just the
2083 standard ASCII character set. Perl supports \fIUnicode\fR, a standard
2084 for representing the alphabets from virtually all of the world\*(Aqs written
2085 languages, and a host of symbols. Perl\*(Aqs text strings are Unicode strings, so
2086 they can contain characters with a value (codepoint or character number) higher
2087 than 255.
2088 .PP
2089 What does this mean for regexps? Well, regexp users don\*(Aqt need to know
2090 much about Perl\*(Aqs internal representation of strings. But they do need
2091 to know 1) how to represent Unicode characters in a regexp and 2) that
2092 a matching operation will treat the string to be searched as a sequence
2093 of characters, not bytes. The answer to 1) is that Unicode characters
2094 greater than \f(CWchr(255)\fR are represented using the \f(CW\*(C`\ex{hex}\*(C'\fR notation, because
2095 \&\f(CW\*(C`\ex\*(C'\fR\fIXY\fR (specified as two hex digits without curly braces) doesn\*(Aqt
2096 go further than 255. (Starting in Perl 5.14, if you\*(Aqre an octal fan,
2097 you can also use \f(CW\*(C`\eo{oct}\*(C'\fR.)
2098 .PP
2099 .Vb 2
2100 \& /\ex{263a}/; # match a Unicode smiley face :)
2101 \& /\ex{ 263a }/; # Same
2102 .Ve
2103 .PP
2104 \&\fBNOTE\fR: In Perl 5.6.0 it used to be that one needed to say \f(CW\*(C`use
2105 utf8\*(C'\fR to use any Unicode features. This is no longer the case: for
2106 almost all Unicode processing, the explicit \f(CW\*(C`utf8\*(C'\fR pragma is not
2107 needed. (The only case where it matters is if your Perl script is in
2108 Unicode and encoded in UTF\-8, then an explicit \f(CW\*(C`use utf8\*(C'\fR is needed.)
2109 .PP
2110 Figuring out the hexadecimal sequence of a Unicode character you want
2111 or deciphering someone else\*(Aqs hexadecimal Unicode regexp is about as
2112 much fun as programming in machine code. So another way to specify
2113 Unicode characters is to use the \fInamed character\fR escape
2114 sequence \f(CW\*(C`\eN{\fR\f(CIname\fR\f(CW}\*(C'\fR. \fIname\fR is a name for the Unicode character, as
2115 specified in the Unicode standard. For instance, if we wanted to
2116 represent or match the astrological sign for the planet Mercury, we
2117 could use
2118 .PP
2119 .Vb 3
2120 \& $x = "abc\eN{MERCURY}def";
2121 \& $x =~ /\eN{MERCURY}/; # matches
2122 \& $x =~ /\eN{ MERCURY }/; # Also matches
2123 .Ve
2124 .PP
2125 One can also use "short" names:
2126 .PP
2127 .Vb 2
2128 \& print "\eN{GREEK SMALL LETTER SIGMA} is called sigma.\en";
2129 \& print "\eN{greek:Sigma} is an upper\-case sigma.\en";
2130 .Ve
2131 .PP
2132 You can also restrict names to a certain alphabet by specifying the
2133 charnames pragma:
2134 .PP
2135 .Vb 2
2136 \& use charnames qw(greek);
2137 \& print "\eN{sigma} is Greek sigma\en";
2138 .Ve
2139 .PP
2140 An index of character names is available on\-line from the Unicode
2141 Consortium, <https://www.unicode.org/charts/charindex.html>; explanatory
2142 material with links to other resources at
2143 <https://www.unicode.org/standard/where>.
2144 .PP
2145 Starting in Perl v5.32, an alternative to \f(CW\*(C`\eN{...}\*(C'\fR for full names is
2146 available, and that is to say
2147 .PP
2148 .Vb 1
2149 \& /\ep{Name=greek small letter sigma}/
2150 .Ve
2151 .PP
2152 The casing of the character name is irrelevant when used in \f(CW\*(C`\ep{}\*(C'\fR, as
2153 are most spaces, underscores and hyphens. (A few outlier characters
2154 cause problems with ignoring all of them always. The details (which you
2155 can look up when you get more proficient, and if ever needed) are in
2156 <https://www.unicode.org/reports/tr44/tr44\-24.html#UAX44\-LM2>).
2157 .PP
2158 The answer to requirement 2) is that a regexp (mostly)
2159 uses Unicode characters. The "mostly" is for messy backward
2160 compatibility reasons, but starting in Perl 5.14, any regexp compiled in
2161 the scope of a \f(CW\*(C`use feature \*(Aqunicode_strings\*(Aq\*(C'\fR (which is automatically
2162 turned on within the scope of a \f(CW\*(C`use v5.12\*(C'\fR or higher) will turn that
2163 "mostly" into "always". If you want to handle Unicode properly, you
2164 should ensure that \f(CW\*(Aqunicode_strings\*(Aq\fR is turned on.
2165 Internally, this is encoded to bytes using either UTF\-8 or a native 8
2166 bit encoding, depending on the history of the string, but conceptually
2167 it is a sequence of characters, not bytes. See perlunitut for a
2168 tutorial about that.
2169 .PP
2170 Let us now discuss Unicode character classes, most usually called
2171 "character properties". These are represented by the \f(CW\*(C`\ep{\fR\f(CIname\fR\f(CW}\*(C'\fR
2172 escape sequence. The negation of this is \f(CW\*(C`\eP{\fR\f(CIname\fR\f(CW}\*(C'\fR. For example,
2173 to match lower and uppercase characters,
2174 .PP
2175 .Vb 5
2176 \& $x = "BOB";
2177 \& $x =~ /^\ep{IsUpper}/; # matches, uppercase char class
2178 \& $x =~ /^\eP{IsUpper}/; # doesn\*(Aqt match, char class sans uppercase
2179 \& $x =~ /^\ep{IsLower}/; # doesn\*(Aqt match, lowercase char class
2180 \& $x =~ /^\eP{IsLower}/; # matches, char class sans lowercase
2181 .Ve
2182 .PP
2183 (The "\f(CW\*(C`Is\*(C'\fR" is optional.)
2184 .PP
2185 There are many, many Unicode character properties. For the full list
2186 see perluniprops. Most of them have synonyms with shorter names,
2187 also listed there. Some synonyms are a single character. For these,
2188 you can drop the braces. For instance, \f(CW\*(C`\epM\*(C'\fR is the same thing as
2189 \&\f(CW\*(C`\ep{Mark}\*(C'\fR, meaning things like accent marks.
2190 .PP
2191 The Unicode \f(CW\*(C`\ep{Script}\*(C'\fR and \f(CW\*(C`\ep{Script_Extensions}\*(C'\fR properties are
2192 used to categorize every Unicode character into the language script it
2193 is written in. For example,
2194 English, French, and a bunch of other European languages are written in
2195 the Latin script. But there is also the Greek script, the Thai script,
2196 the Katakana script, \fIetc\fR. (\f(CW\*(C`Script\*(C'\fR is an older, less advanced,
2197 form of \f(CW\*(C`Script_Extensions\*(C'\fR, retained only for backwards
2198 compatibility.) You can test whether a character is in a particular
2199 script with, for example \f(CW\*(C`\ep{Latin}\*(C'\fR, \f(CW\*(C`\ep{Greek}\*(C'\fR, or
2200 \&\f(CW\*(C`\ep{Katakana}\*(C'\fR. To test if it isn\*(Aqt in the Balinese script, you would
2201 use \f(CW\*(C`\eP{Balinese}\*(C'\fR. (These all use \f(CW\*(C`Script_Extensions\*(C'\fR under the
2202 hood, as that gives better results.)
2203 .PP
2204 What we have described so far is the single form of the \f(CW\*(C`\ep{...}\*(C'\fR character
2205 classes. There is also a compound form which you may run into. These
2206 look like \f(CW\*(C`\ep{\fR\f(CIname\fR\f(CW=\fR\f(CIvalue\fR\f(CW}\*(C'\fR or \f(CW\*(C`\ep{\fR\f(CIname\fR\f(CW:\fR\f(CIvalue\fR\f(CW}\*(C'\fR (the equals sign and colon
2207 can be used interchangeably). These are more general than the single form,
2208 and in fact most of the single forms are just Perl\-defined shortcuts for common
2209 compound forms. For example, the script examples in the previous paragraph
2210 could be written equivalently as \f(CW\*(C`\ep{Script_Extensions=Latin}\*(C'\fR, \f(CW\*(C`\ep{Script_Extensions:Greek}\*(C'\fR,
2211 \&\f(CW\*(C`\ep{script_extensions=katakana}\*(C'\fR, and \f(CW\*(C`\eP{script_extensions=balinese}\*(C'\fR (case is irrelevant
2212 between the \f(CW\*(C`{}\*(C'\fR braces). You may
2213 never have to use the compound forms, but sometimes it is necessary, and their
2214 use can make your code easier to understand.
2215 .PP
2216 \&\f(CW\*(C`\eX\*(C'\fR is an abbreviation for a character class that comprises
2217 a Unicode \fIextended grapheme cluster\fR. This represents a "logical character":
2218 what appears to be a single character, but may be represented internally by more
2219 than one. As an example, using the Unicode full names, \fIe.g.\fR, "A\ +\ COMBINING\ RING" is a grapheme cluster with base character "A" and combining character
2220 "COMBINING\ RING, which translates in Danish to "A" with the circle atop it,
2221 as in the word Ã…ngstrom.
2222 .PP
2223 For the full and latest information about Unicode see the latest
2224 Unicode standard, or the Unicode Consortium\*(Aqs website <https://www.unicode.org>
2225 .PP
2226 As if all those classes weren\*(Aqt enough, Perl also defines POSIX\-style
2227 character classes. These have the form \f(CW\*(C`[:\fR\f(CIname\fR\f(CW:]\*(C'\fR, with \fIname\fR the
2228 name of the POSIX class. The POSIX classes are \f(CW\*(C`alpha\*(C'\fR, \f(CW\*(C`alnum\*(C'\fR,
2229 \&\f(CW\*(C`ascii\*(C'\fR, \f(CW\*(C`blank\*(C'\fR, \f(CW\*(C`cntrl\*(C'\fR, \f(CW\*(C`digit\*(C'\fR, \f(CW\*(C`graph\*(C'\fR, \f(CW\*(C`lower\*(C'\fR, \f(CW\*(C`print\*(C'\fR,
2230 \&\f(CW\*(C`punct\*(C'\fR, \f(CW\*(C`space\*(C'\fR, \f(CW\*(C`upper\*(C'\fR, \f(CW\*(C`xdigit\*(C'\fR, and \f(CW\*(C`word\*(C'\fR (a Perl extension to
2231 match \f(CW\*(C`\ew\*(C'\fR). The \f(CW\*(C`/a\*(C'\fR
2232 modifier restricts these to matching just in the ASCII range; otherwise
2233 they can match the same as their corresponding Perl Unicode classes:
2234 \&\f(CW\*(C`[:upper:]\*(C'\fR is the same as \f(CW\*(C`\ep{IsUpper}\*(C'\fR, \fIetc\fR. (There are some
2235 exceptions and gotchas with this; see perlrecharclass for a full
2236 discussion.) The \f(CW\*(C`[:digit:]\*(C'\fR, \f(CW\*(C`[:word:]\*(C'\fR, and
2237 \&\f(CW\*(C`[:space:]\*(C'\fR correspond to the familiar \f(CW\*(C`\ed\*(C'\fR, \f(CW\*(C`\ew\*(C'\fR, and \f(CW\*(C`\es\*(C'\fR
2238 character classes. To negate a POSIX class, put a \f(CW\*(Aq^\*(Aq\fR in front of
2239 the name, so that, \fIe.g.\fR, \f(CW\*(C`[:^digit:]\*(C'\fR corresponds to \f(CW\*(C`\eD\*(C'\fR and, under
2240 Unicode, \f(CW\*(C`\eP{IsDigit}\*(C'\fR. The Unicode and POSIX character classes can
2241 be used just like \f(CW\*(C`\ed\*(C'\fR, with the exception that POSIX character
2242 classes can only be used inside of a character class:
2243 .PP
2244 .Vb 6
2245 \& /\es+[abc[:digit:]xyz]\es*/; # match a,b,c,x,y,z, or a digit
2246 \& /^=item\es[[:digit:]]/; # match \*(Aq=item\*(Aq,
2247 \& # followed by a space and a digit
2248 \& /\es+[abc\ep{IsDigit}xyz]\es+/; # match a,b,c,x,y,z, or a digit
2249 \& /^=item\es\ep{IsDigit}/; # match \*(Aq=item\*(Aq,
2250 \& # followed by a space and a digit
2251 .Ve
2252 .PP
2253 Whew! That is all the rest of the characters and character classes.
2254 .SS "Compiling and saving regular expressions"
2255 .IX Subsection "Compiling and saving regular expressions"
2256 In Part 1 we mentioned that Perl compiles a regexp into a compact
2257 sequence of opcodes. Thus, a compiled regexp is a data structure
2258 that can be stored once and used again and again. The regexp quote
2259 \&\f(CW\*(C`qr//\*(C'\fR does exactly that: \f(CW\*(C`qr/string/\*(C'\fR compiles the \f(CW\*(C`string\*(C'\fR as a
2260 regexp and transforms the result into a form that can be assigned to a
2261 variable:
2262 .PP
2263 .Vb 1
2264 \& $reg = qr/foo+bar?/; # reg contains a compiled regexp
2265 .Ve
2266 .PP
2267 Then \f(CW$reg\fR can be used as a regexp:
2268 .PP
2269 .Vb 3
2270 \& $x = "fooooba";
2271 \& $x =~ $reg; # matches, just like /foo+bar?/
2272 \& $x =~ /$reg/; # same thing, alternate form
2273 .Ve
2274 .PP
2275 \&\f(CW$reg\fR can also be interpolated into a larger regexp:
2276 .PP
2277 .Vb 1
2278 \& $x =~ /(abc)?$reg/; # still matches
2279 .Ve
2280 .PP
2281 As with the matching operator, the regexp quote can use different
2282 delimiters, \fIe.g.\fR, \f(CW\*(C`qr!!\*(C'\fR, \f(CW\*(C`qr{}\*(C'\fR or \f(CW\*(C`qr~~\*(C'\fR. Apostrophes
2283 as delimiters (\f(CW\*(C`qr\*(Aq\*(Aq\*(C'\fR) inhibit any interpolation.
2284 .PP
2285 Pre\-compiled regexps are useful for creating dynamic matches that
2286 don\*(Aqt need to be recompiled each time they are encountered. Using
2287 pre\-compiled regexps, we write a \f(CW\*(C`grep_step\*(C'\fR program which greps
2288 for a sequence of patterns, advancing to the next pattern as soon
2289 as one has been satisfied.
2290 .PP
2291 .Vb 4
2292 \& % cat > grep_step
2293 \& #!/usr/bin/perl
2294 \& # grep_step \- match <number> regexps, one after the other
2295 \& # usage: multi_grep <number> regexp1 regexp2 ... file1 file2 ...
2296 \&
2297 \& $number = shift;
2298 \& $regexp[$_] = shift foreach (0..$number\-1);
2299 \& @compiled = map qr/$_/, @regexp;
2300 \& while ($line = <>) {
2301 \& if ($line =~ /$compiled[0]/) {
2302 \& print $line;
2303 \& shift @compiled;
2304 \& last unless @compiled;
2305 \& }
2306 \& }
2307 \& ^D
2308 \&
2309 \& % grep_step 3 shift print last grep_step
2310 \& $number = shift;
2311 \& print $line;
2312 \& last unless @compiled;
2313 .Ve
2314 .PP
2315 Storing pre\-compiled regexps in an array \f(CW@compiled\fR allows us to
2316 simply loop through the regexps without any recompilation, thus gaining
2317 flexibility without sacrificing speed.
2318 .SS "Composing regular expressions at runtime"
2319 .IX Subsection "Composing regular expressions at runtime"
2320 Backtracking is more efficient than repeated tries with different regular
2321 expressions. If there are several regular expressions and a match with
2322 any of them is acceptable, then it is possible to combine them into a set
2323 of alternatives. If the individual expressions are input data, this
2324 can be done by programming a join operation. We\*(Aqll exploit this idea in
2325 an improved version of the \f(CW\*(C`simple_grep\*(C'\fR program: a program that matches
2326 multiple patterns:
2327 .PP
2328 .Vb 4
2329 \& % cat > multi_grep
2330 \& #!/usr/bin/perl
2331 \& # multi_grep \- match any of <number> regexps
2332 \& # usage: multi_grep <number> regexp1 regexp2 ... file1 file2 ...
2333 \&
2334 \& $number = shift;
2335 \& $regexp[$_] = shift foreach (0..$number\-1);
2336 \& $pattern = join \*(Aq|\*(Aq, @regexp;
2337 \&
2338 \& while ($line = <>) {
2339 \& print $line if $line =~ /$pattern/;
2340 \& }
2341 \& ^D
2342 \&
2343 \& % multi_grep 2 shift for multi_grep
2344 \& $number = shift;
2345 \& $regexp[$_] = shift foreach (0..$number\-1);
2346 .Ve
2347 .PP
2348 Sometimes it is advantageous to construct a pattern from the \fIinput\fR
2349 that is to be analyzed and use the permissible values on the left
2350 hand side of the matching operations. As an example for this somewhat
2351 paradoxical situation, let\*(Aqs assume that our input contains a command
2352 verb which should match one out of a set of available command verbs,
2353 with the additional twist that commands may be abbreviated as long as
2354 the given string is unique. The program below demonstrates the basic
2355 algorithm.
2356 .PP
2357 .Vb 10
2358 \& % cat > keymatch
2359 \& #!/usr/bin/perl
2360 \& $kwds = \*(Aqcopy compare list print\*(Aq;
2361 \& while( $cmd = <> ){
2362 \& $cmd =~ s/^\es+|\es+$//g; # trim leading and trailing spaces
2363 \& if( ( @matches = $kwds =~ /\eb$cmd\ew*/g ) == 1 ){
2364 \& print "command: \*(Aq@matches\*(Aq\en";
2365 \& } elsif( @matches == 0 ){
2366 \& print "no such command: \*(Aq$cmd\*(Aq\en";
2367 \& } else {
2368 \& print "not unique: \*(Aq$cmd\*(Aq (could be one of: @matches)\en";
2369 \& }
2370 \& }
2371 \& ^D
2372 \&
2373 \& % keymatch
2374 \& li
2375 \& command: \*(Aqlist\*(Aq
2376 \& co
2377 \& not unique: \*(Aqco\*(Aq (could be one of: copy compare)
2378 \& printer
2379 \& no such command: \*(Aqprinter\*(Aq
2380 .Ve
2381 .PP
2382 Rather than trying to match the input against the keywords, we match the
2383 combined set of keywords against the input. The pattern matching
2384 operation \f(CW\*(C`$kwds\ =~\ /\eb($cmd\ew*)/g\*(C'\fR does several things at the
2385 same time. It makes sure that the given command begins where a keyword
2386 begins (\f(CW\*(C`\eb\*(C'\fR). It tolerates abbreviations due to the added \f(CW\*(C`\ew*\*(C'\fR. It
2387 tells us the number of matches (\f(CW\*(C`scalar @matches\*(C'\fR) and all the keywords
2388 that were actually matched. You could hardly ask for more.
2389 .SS "Embedding comments and modifiers in a regular expression"
2390 .IX Subsection "Embedding comments and modifiers in a regular expression"
2391 Starting with this section, we will be discussing Perl\*(Aqs set of
2392 \&\fIextended patterns\fR. These are extensions to the traditional regular
2393 expression syntax that provide powerful new tools for pattern
2394 matching. We have already seen extensions in the form of the minimal
2395 matching constructs \f(CW\*(C`??\*(C'\fR, \f(CW\*(C`*?\*(C'\fR, \f(CW\*(C`+?\*(C'\fR, \f(CW\*(C`{n,m}?\*(C'\fR, \f(CW\*(C`{n,}?\*(C'\fR, and
2396 \&\f(CW\*(C`{,n}?\*(C'\fR. Most of the extensions below have the form \f(CW\*(C`(?char...)\*(C'\fR,
2397 where the \f(CW\*(C`char\*(C'\fR is a character that determines the type of extension.
2398 .PP
2399 The first extension is an embedded comment \f(CW\*(C`(?#text)\*(C'\fR. This embeds a
2400 comment into the regular expression without affecting its meaning. The
2401 comment should not have any closing parentheses in the text. An
2402 example is
2403 .PP
2404 .Vb 1
2405 \& /(?# Match an integer:)[+\-]?\ed+/;
2406 .Ve
2407 .PP
2408 This style of commenting has been largely superseded by the raw,
2409 freeform commenting that is allowed with the \f(CW\*(C`/x\*(C'\fR modifier.
2410 .PP
2411 Most modifiers, such as \f(CW\*(C`/i\*(C'\fR, \f(CW\*(C`/m\*(C'\fR, \f(CW\*(C`/s\*(C'\fR and \f(CW\*(C`/x\*(C'\fR (or any
2412 combination thereof) can also be embedded in
2413 a regexp using \f(CW\*(C`(?i)\*(C'\fR, \f(CW\*(C`(?m)\*(C'\fR, \f(CW\*(C`(?s)\*(C'\fR, and \f(CW\*(C`(?x)\*(C'\fR. For instance,
2414 .PP
2415 .Vb 7
2416 \& /(?i)yes/; # match \*(Aqyes\*(Aq case insensitively
2417 \& /yes/i; # same thing
2418 \& /(?x)( # freeform version of an integer regexp
2419 \& [+\-]? # match an optional sign
2420 \& \ed+ # match a sequence of digits
2421 \& )
2422 \& /x;
2423 .Ve
2424 .PP
2425 Embedded modifiers can have two important advantages over the usual
2426 modifiers. Embedded modifiers allow a custom set of modifiers for
2427 \&\fIeach\fR regexp pattern. This is great for matching an array of regexps
2428 that must have different modifiers:
2429 .PP
2430 .Vb 8
2431 \& $pattern[0] = \*(Aq(?i)doctor\*(Aq;
2432 \& $pattern[1] = \*(AqJohnson\*(Aq;
2433 \& ...
2434 \& while (<>) {
2435 \& foreach $patt (@pattern) {
2436 \& print if /$patt/;
2437 \& }
2438 \& }
2439 .Ve
2440 .PP
2441 The second advantage is that embedded modifiers (except \f(CW\*(C`/p\*(C'\fR, which
2442 modifies the entire regexp) only affect the regexp
2443 inside the group the embedded modifier is contained in. So grouping
2444 can be used to localize the modifier\*(Aqs effects:
2445 .PP
2446 .Vb 1
2447 \& /Answer: ((?i)yes)/; # matches \*(AqAnswer: yes\*(Aq, \*(AqAnswer: YES\*(Aq, etc.
2448 .Ve
2449 .PP
2450 Embedded modifiers can also turn off any modifiers already present
2451 by using, \fIe.g.\fR, \f(CW\*(C`(?\-i)\*(C'\fR. Modifiers can also be combined into
2452 a single expression, \fIe.g.\fR, \f(CW\*(C`(?s\-i)\*(C'\fR turns on single line mode and
2453 turns off case insensitivity.
2454 .PP
2455 Embedded modifiers may also be added to a non\-capturing grouping.
2456 \&\f(CW\*(C`(?i\-m:regexp)\*(C'\fR is a non\-capturing grouping that matches \f(CW\*(C`regexp\*(C'\fR
2457 case insensitively and turns off multi\-line mode.
2458 .SS "Looking ahead and looking behind"
2459 .IX Subsection "Looking ahead and looking behind"
2460 This section concerns the lookahead and lookbehind assertions. First,
2461 a little background.
2462 .PP
2463 In Perl regular expressions, most regexp elements "eat up" a certain
2464 amount of string when they match. For instance, the regexp element
2465 \&\f(CW\*(C`[abc]\*(C'\fR eats up one character of the string when it matches, in the
2466 sense that Perl moves to the next character position in the string
2467 after the match. There are some elements, however, that don\*(Aqt eat up
2468 characters (advance the character position) if they match. The examples
2469 we have seen so far are the anchors. The anchor \f(CW\*(Aq^\*(Aq\fR matches the
2470 beginning of the line, but doesn\*(Aqt eat any characters. Similarly, the
2471 word boundary anchor \f(CW\*(C`\eb\*(C'\fR matches wherever a character matching \f(CW\*(C`\ew\*(C'\fR
2472 is next to a character that doesn\*(Aqt, but it doesn\*(Aqt eat up any
2473 characters itself. Anchors are examples of \fIzero\-width assertions\fR:
2474 zero\-width, because they consume
2475 no characters, and assertions, because they test some property of the
2476 string. In the context of our walk in the woods analogy to regexp
2477 matching, most regexp elements move us along a trail, but anchors have
2478 us stop a moment and check our surroundings. If the local environment
2479 checks out, we can proceed forward. But if the local environment
2480 doesn\*(Aqt satisfy us, we must backtrack.
2481 .PP
2482 Checking the environment entails either looking ahead on the trail,
2483 looking behind, or both. \f(CW\*(Aq^\*(Aq\fR looks behind, to see that there are no
2484 characters before. \f(CW\*(Aq$\*(Aq\fR looks ahead, to see that there are no
2485 characters after. \f(CW\*(C`\eb\*(C'\fR looks both ahead and behind, to see if the
2486 characters on either side differ in their "word\-ness".
2487 .PP
2488 The lookahead and lookbehind assertions are generalizations of the
2489 anchor concept. Lookahead and lookbehind are zero\-width assertions
2490 that let us specify which characters we want to test for. The
2491 lookahead assertion is denoted by \f(CW\*(C`(?=regexp)\*(C'\fR or (starting in 5.32,
2492 experimentally in 5.28) \f(CW\*(C`(*pla:regexp)\*(C'\fR or
2493 \&\f(CW\*(C`(*positive_lookahead:regexp)\*(C'\fR; and the lookbehind assertion is denoted
2494 by \f(CW\*(C`(?<=fixed\-regexp)\*(C'\fR or (starting in 5.32, experimentally in
2495 5.28) \f(CW\*(C`(*plb:fixed\-regexp)\*(C'\fR or \f(CW\*(C`(*positive_lookbehind:fixed\-regexp)\*(C'\fR.
2496 Some examples are
2497 .PP
2498 .Vb 8
2499 \& $x = "I catch the housecat \*(AqTom\-cat\*(Aq with catnip";
2500 \& $x =~ /cat(*pla:\es)/; # matches \*(Aqcat\*(Aq in \*(Aqhousecat\*(Aq
2501 \& @catwords = ($x =~ /(?<=\es)cat\ew+/g); # matches,
2502 \& # $catwords[0] = \*(Aqcatch\*(Aq
2503 \& # $catwords[1] = \*(Aqcatnip\*(Aq
2504 \& $x =~ /\ebcat\eb/; # matches \*(Aqcat\*(Aq in \*(AqTom\-cat\*(Aq
2505 \& $x =~ /(?<=\es)cat(?=\es)/; # doesn\*(Aqt match; no isolated \*(Aqcat\*(Aq in
2506 \& # middle of $x
2507 .Ve
2508 .PP
2509 Note that the parentheses in these are
2510 non\-capturing, since these are zero\-width assertions. Thus in the
2511 second regexp, the substrings captured are those of the whole regexp
2512 itself. Lookahead can match arbitrary regexps, but
2513 lookbehind prior to 5.30 \f(CW\*(C`(?<=fixed\-regexp)\*(C'\fR only works for regexps
2514 of fixed width, \fIi.e.\fR, a fixed number of characters long. Thus
2515 \&\f(CW\*(C`(?<=(ab|bc))\*(C'\fR is fine, but \f(CW\*(C`(?<=(ab)*)\*(C'\fR prior to 5.30 is not.
2516 .PP
2517 The negated versions of the lookahead and lookbehind assertions are
2518 denoted by \f(CW\*(C`(?!regexp)\*(C'\fR and \f(CW\*(C`(?<!fixed\-regexp)\*(C'\fR respectively.
2519 Or, starting in 5.32 (experimentally in 5.28), \f(CW\*(C`(*nla:regexp)\*(C'\fR,
2520 \&\f(CW\*(C`(*negative_lookahead:regexp)\*(C'\fR, \f(CW\*(C`(*nlb:regexp)\*(C'\fR, or
2521 \&\f(CW\*(C`(*negative_lookbehind:regexp)\*(C'\fR.
2522 They evaluate true if the regexps do \fInot\fR match:
2523 .PP
2524 .Vb 4
2525 \& $x = "foobar";
2526 \& $x =~ /foo(?!bar)/; # doesn\*(Aqt match, \*(Aqbar\*(Aq follows \*(Aqfoo\*(Aq
2527 \& $x =~ /foo(?!baz)/; # matches, \*(Aqbaz\*(Aq doesn\*(Aqt follow \*(Aqfoo\*(Aq
2528 \& $x =~ /(?<!\es)foo/; # matches, there is no \es before \*(Aqfoo\*(Aq
2529 .Ve
2530 .PP
2531 Here is an example where a string containing blank\-separated words,
2532 numbers and single dashes is to be split into its components.
2533 Using \f(CW\*(C`/\es+/\*(C'\fR alone won\*(Aqt work, because spaces are not required between
2534 dashes, or a word or a dash. Additional places for a split are established
2535 by looking ahead and behind:
2536 .PP
2537 .Vb 5
2538 \& $str = "one two \- \-\-6\-8";
2539 \& @toks = split / \es+ # a run of spaces
2540 \& | (?<=\eS) (?=\-) # any non\-space followed by \*(Aq\-\*(Aq
2541 \& | (?<=\-) (?=\eS) # a \*(Aq\-\*(Aq followed by any non\-space
2542 \& /x, $str; # @toks = qw(one two \- \- \- 6 \- 8)
2543 .Ve
2544 .SS "Using independent subexpressions to prevent backtracking"
2545 .IX Subsection "Using independent subexpressions to prevent backtracking"
2546 \&\fIIndependent subexpressions\fR (or atomic subexpressions) are regular
2547 expressions, in the context of a larger regular expression, that
2548 function independently of the larger regular expression. That is, they
2549 consume as much or as little of the string as they wish without regard
2550 for the ability of the larger regexp to match. Independent
2551 subexpressions are represented by
2552 \&\f(CW\*(C`(?>regexp)\*(C'\fR or (starting in 5.32, experimentally in 5.28)
2553 \&\f(CW\*(C`(*atomic:regexp)\*(C'\fR. We can illustrate their behavior by first
2554 considering an ordinary regexp:
2555 .PP
2556 .Vb 2
2557 \& $x = "ab";
2558 \& $x =~ /a*ab/; # matches
2559 .Ve
2560 .PP
2561 This obviously matches, but in the process of matching, the
2562 subexpression \f(CW\*(C`a*\*(C'\fR first grabbed the \f(CW\*(Aqa\*(Aq\fR. Doing so, however,
2563 wouldn\*(Aqt allow the whole regexp to match, so after backtracking, \f(CW\*(C`a*\*(C'\fR
2564 eventually gave back the \f(CW\*(Aqa\*(Aq\fR and matched the empty string. Here, what
2565 \&\f(CW\*(C`a*\*(C'\fR matched was \fIdependent\fR on what the rest of the regexp matched.
2566 .PP
2567 Contrast that with an independent subexpression:
2568 .PP
2569 .Vb 1
2570 \& $x =~ /(?>a*)ab/; # doesn\*(Aqt match!
2571 .Ve
2572 .PP
2573 The independent subexpression \f(CW\*(C`(?>a*)\*(C'\fR doesn\*(Aqt care about the rest
2574 of the regexp, so it sees an \f(CW\*(Aqa\*(Aq\fR and grabs it. Then the rest of the
2575 regexp \f(CW\*(C`ab\*(C'\fR cannot match. Because \f(CW\*(C`(?>a*)\*(C'\fR is independent, there
2576 is no backtracking and the independent subexpression does not give
2577 up its \f(CW\*(Aqa\*(Aq\fR. Thus the match of the regexp as a whole fails. A similar
2578 behavior occurs with completely independent regexps:
2579 .PP
2580 .Vb 3
2581 \& $x = "ab";
2582 \& $x =~ /a*/g; # matches, eats an \*(Aqa\*(Aq
2583 \& $x =~ /\eGab/g; # doesn\*(Aqt match, no \*(Aqa\*(Aq available
2584 .Ve
2585 .PP
2586 Here \f(CW\*(C`/g\*(C'\fR and \f(CW\*(C`\eG\*(C'\fR create a "tag team" handoff of the string from
2587 one regexp to the other. Regexps with an independent subexpression are
2588 much like this, with a handoff of the string to the independent
2589 subexpression, and a handoff of the string back to the enclosing
2590 regexp.
2591 .PP
2592 The ability of an independent subexpression to prevent backtracking
2593 can be quite useful. Suppose we want to match a non\-empty string
2594 enclosed in parentheses up to two levels deep. Then the following
2595 regexp matches:
2596 .PP
2597 .Vb 2
2598 \& $x = "abc(de(fg)h"; # unbalanced parentheses
2599 \& $x =~ /\e( ( [ ^ () ]+ | \e( [ ^ () ]* \e) )+ \e)/xx;
2600 .Ve
2601 .PP
2602 The regexp matches an open parenthesis, one or more copies of an
2603 alternation, and a close parenthesis. The alternation is two\-way, with
2604 the first alternative \f(CW\*(C`[^()]+\*(C'\fR matching a substring with no
2605 parentheses and the second alternative \f(CW\*(C`\e([^()]*\e)\*(C'\fR matching a
2606 substring delimited by parentheses. The problem with this regexp is
2607 that it is pathological: it has nested indeterminate quantifiers
2608 of the form \f(CW\*(C`(a+|b)+\*(C'\fR. We discussed in Part 1 how nested quantifiers
2609 like this could take an exponentially long time to execute if there
2610 is no match possible. To prevent the exponential blowup, we need to
2611 prevent useless backtracking at some point. This can be done by
2612 enclosing the inner quantifier as an independent subexpression:
2613 .PP
2614 .Vb 1
2615 \& $x =~ /\e( ( (?> [ ^ () ]+ ) | \e([ ^ () ]* \e) )+ \e)/xx;
2616 .Ve
2617 .PP
2618 Here, \f(CW\*(C`(?>[^()]+)\*(C'\fR breaks the degeneracy of string partitioning
2619 by gobbling up as much of the string as possible and keeping it. Then
2620 match failures fail much more quickly.
2621 .SS "Conditional expressions"
2622 .IX Subsection "Conditional expressions"
2623 A \fIconditional expression\fR is a form of if\-then\-else statement
2624 that allows one to choose which patterns are to be matched, based on
2625 some condition. There are two types of conditional expression:
2626 \&\f(CW\*(C`(?(\fR\f(CIcondition\fR\f(CW)\fR\f(CIyes\-regexp\fR\f(CW)\*(C'\fR and
2627 \&\f(CW\*(C`(?(condition)\fR\f(CIyes\-regexp\fR\f(CW|\fR\f(CIno\-regexp\fR\f(CW)\*(C'\fR.
2628 \&\f(CW\*(C`(?(\fR\f(CIcondition\fR\f(CW)\fR\f(CIyes\-regexp\fR\f(CW)\*(C'\fR is
2629 like an \f(CW\*(Aqif\ ()\ {}\*(Aq\fR statement in Perl. If the \fIcondition\fR is true,
2630 the \fIyes\-regexp\fR will be matched. If the \fIcondition\fR is false, the
2631 \&\fIyes\-regexp\fR will be skipped and Perl will move onto the next regexp
2632 element. The second form is like an \f(CW\*(Aqif\ ()\ {}\ else\ {}\*(Aq\fR statement
2633 in Perl. If the \fIcondition\fR is true, the \fIyes\-regexp\fR will be
2634 matched, otherwise the \fIno\-regexp\fR will be matched.
2635 .PP
2636 The \fIcondition\fR can have several forms. The first form is simply an
2637 integer in parentheses \f(CW\*(C`(\fR\f(CIinteger\fR\f(CW)\*(C'\fR. It is true if the corresponding
2638 backreference \f(CW\*(C`\e\fR\f(CIinteger\fR\f(CW\*(C'\fR matched earlier in the regexp. The same
2639 thing can be done with a name associated with a capture group, written
2640 as \f(CW\*(C`(<\fR\f(CIname\fR\f(CW>)\*(C'\fR or \f(CW\*(C`(\*(Aq\fR\f(CIname\fR\f(CW\*(Aq)\*(C'\fR. The second form is a bare
2641 zero\-width assertion \f(CW\*(C`(?...)\*(C'\fR, either a lookahead, a lookbehind, or a
2642 code assertion (discussed in the next section). The third set of forms
2643 provides tests that return true if the expression is executed within
2644 a recursion (\f(CW\*(C`(R)\*(C'\fR) or is being called from some capturing group,
2645 referenced either by number (\f(CW\*(C`(R1)\*(C'\fR, \f(CW\*(C`(R2)\*(C'\fR,...) or by name
2646 (\f(CW\*(C`(R&\fR\f(CIname\fR\f(CW)\*(C'\fR).
2647 .PP
2648 The integer or name form of the \f(CW\*(C`condition\*(C'\fR allows us to choose,
2649 with more flexibility, what to match based on what matched earlier in the
2650 regexp. This searches for words of the form \f(CW"$x$x"\fR or \f(CW"$x$y$y$x"\fR:
2651 .PP
2652 .Vb 9
2653 \& % simple_grep \*(Aq^(\ew+)(\ew+)?(?(2)\eg2\eg1|\eg1)$\*(Aq /usr/dict/words
2654 \& beriberi
2655 \& coco
2656 \& couscous
2657 \& deed
2658 \& ...
2659 \& toot
2660 \& toto
2661 \& tutu
2662 .Ve
2663 .PP
2664 The lookbehind \f(CW\*(C`condition\*(C'\fR allows, along with backreferences,
2665 an earlier part of the match to influence a later part of the
2666 match. For instance,
2667 .PP
2668 .Vb 1
2669 \& /[ATGC]+(?(?<=AA)G|C)$/;
2670 .Ve
2671 .PP
2672 matches a DNA sequence such that it either ends in \f(CW\*(C`AAG\*(C'\fR, or some
2673 other base pair combination and \f(CW\*(AqC\*(Aq\fR. Note that the form is
2674 \&\f(CW\*(C`(?(?<=AA)G|C)\*(C'\fR and not \f(CW\*(C`(?((?<=AA))G|C)\*(C'\fR; for the
2675 lookahead, lookbehind or code assertions, the parentheses around the
2676 conditional are not needed.
2677 .SS "Defining named patterns"
2678 .IX Subsection "Defining named patterns"
2679 Some regular expressions use identical subpatterns in several places.
2680 Starting with Perl 5.10, it is possible to define named subpatterns in
2681 a section of the pattern so that they can be called up by name
2682 anywhere in the pattern. This syntactic pattern for this definition
2683 group is \f(CW\*(C`(?(DEFINE)(?<\fR\f(CIname\fR\f(CW>\fR\f(CIpattern\fR\f(CW)...)\*(C'\fR. An insertion
2684 of a named pattern is written as \f(CW\*(C`(?&\fR\f(CIname\fR\f(CW)\*(C'\fR.
2685 .PP
2686 The example below illustrates this feature using the pattern for
2687 floating point numbers that was presented earlier on. The three
2688 subpatterns that are used more than once are the optional sign, the
2689 digit sequence for an integer and the decimal fraction. The \f(CW\*(C`DEFINE\*(C'\fR
2690 group at the end of the pattern contains their definition. Notice
2691 that the decimal fraction pattern is the first place where we can
2692 reuse the integer pattern.
2693 .PP
2694 .Vb 8
2695 \& /^ (?&osg)\e * ( (?&int)(?&dec)? | (?&dec) )
2696 \& (?: [eE](?&osg)(?&int) )?
2697 \& $
2698 \& (?(DEFINE)
2699 \& (?<osg>[\-+]?) # optional sign
2700 \& (?<int>\ed++) # integer
2701 \& (?<dec>\e.(?&int)) # decimal fraction
2702 \& )/x
2703 .Ve
2704 .SS "Recursive patterns"
2705 .IX Subsection "Recursive patterns"
2706 This feature (introduced in Perl 5.10) significantly extends the
2707 power of Perl\*(Aqs pattern matching. By referring to some other
2708 capture group anywhere in the pattern with the construct
2709 \&\f(CW\*(C`(?\fR\f(CIgroup\-ref\fR\f(CW)\*(C'\fR, the \fIpattern\fR within the referenced group is used
2710 as an independent subpattern in place of the group reference itself.
2711 Because the group reference may be contained \fIwithin\fR the group it
2712 refers to, it is now possible to apply pattern matching to tasks that
2713 hitherto required a recursive parser.
2714 .PP
2715 To illustrate this feature, we\*(Aqll design a pattern that matches if
2716 a string contains a palindrome. (This is a word or a sentence that,
2717 while ignoring spaces, interpunctuation and case, reads the same backwards
2718 as forwards. We begin by observing that the empty string or a string
2719 containing just one word character is a palindrome. Otherwise it must
2720 have a word character up front and the same at its end, with another
2721 palindrome in between.
2722 .PP
2723 .Vb 1
2724 \& /(?: (\ew) (?...Here be a palindrome...) \eg{ \-1 } | \ew? )/x
2725 .Ve
2726 .PP
2727 Adding \f(CW\*(C`\eW*\*(C'\fR at either end to eliminate what is to be ignored, we already
2728 have the full pattern:
2729 .PP
2730 .Vb 4
2731 \& my $pp = qr/^(\eW* (?: (\ew) (?1) \eg{\-1} | \ew? ) \eW*)$/ix;
2732 \& for $s ( "saippuakauppias", "A man, a plan, a canal: Panama!" ){
2733 \& print "\*(Aq$s\*(Aq is a palindrome\en" if $s =~ /$pp/;
2734 \& }
2735 .Ve
2736 .PP
2737 In \f(CW\*(C`(?...)\*(C'\fR both absolute and relative backreferences may be used.
2738 The entire pattern can be reinserted with \f(CW\*(C`(?R)\*(C'\fR or \f(CW\*(C`(?0)\*(C'\fR.
2739 If you prefer to name your groups, you can use \f(CW\*(C`(?&\fR\f(CIname\fR\f(CW)\*(C'\fR to
2740 recurse into that group.
2741 .SS "A bit of magic: executing Perl code in a regular expression"
2742 .IX Subsection "A bit of magic: executing Perl code in a regular expression"
2743 Normally, regexps are a part of Perl expressions.
2744 \&\fICode evaluation\fR expressions turn that around by allowing
2745 arbitrary Perl code to be a part of a regexp. A code evaluation
2746 expression is denoted \f(CW\*(C`(?{\fR\f(CIcode\fR\f(CW})\*(C'\fR, with \fIcode\fR a string of Perl
2747 statements.
2748 .PP
2749 Code expressions are zero\-width assertions, and the value they return
2750 depends on their environment. There are two possibilities: either the
2751 code expression is used as a conditional in a conditional expression
2752 \&\f(CW\*(C`(?(\fR\f(CIcondition\fR\f(CW)...)\*(C'\fR, or it is not. If the code expression is a
2753 conditional, the code is evaluated and the result (\fIi.e.\fR, the result of
2754 the last statement) is used to determine truth or falsehood. If the
2755 code expression is not used as a conditional, the assertion always
2756 evaluates true and the result is put into the special variable
2757 \&\f(CW$^R\fR. The variable \f(CW$^R\fR can then be used in code expressions later
2758 in the regexp. Here are some silly examples:
2759 .PP
2760 .Vb 5
2761 \& $x = "abcdef";
2762 \& $x =~ /abc(?{print "Hi Mom!";})def/; # matches,
2763 \& # prints \*(AqHi Mom!\*(Aq
2764 \& $x =~ /aaa(?{print "Hi Mom!";})def/; # doesn\*(Aqt match,
2765 \& # no \*(AqHi Mom!\*(Aq
2766 .Ve
2767 .PP
2768 Pay careful attention to the next example:
2769 .PP
2770 .Vb 3
2771 \& $x =~ /abc(?{print "Hi Mom!";})ddd/; # doesn\*(Aqt match,
2772 \& # no \*(AqHi Mom!\*(Aq
2773 \& # but why not?
2774 .Ve
2775 .PP
2776 At first glance, you\*(Aqd think that it shouldn\*(Aqt print, because obviously
2777 the \f(CW\*(C`ddd\*(C'\fR isn\*(Aqt going to match the target string. But look at this
2778 example:
2779 .PP
2780 .Vb 2
2781 \& $x =~ /abc(?{print "Hi Mom!";})[dD]dd/; # doesn\*(Aqt match,
2782 \& # but _does_ print
2783 .Ve
2784 .PP
2785 Hmm. What happened here? If you\*(Aqve been following along, you know that
2786 the above pattern should be effectively (almost) the same as the last one;
2787 enclosing the \f(CW\*(Aqd\*(Aq\fR in a character class isn\*(Aqt going to change what it
2788 matches. So why does the first not print while the second one does?
2789 .PP
2790 The answer lies in the optimizations the regexp engine makes. In the first
2791 case, all the engine sees are plain old characters (aside from the
2792 \&\f(CW\*(C`?{}\*(C'\fR construct). It\*(Aqs smart enough to realize that the string \f(CW\*(Aqddd\*(Aq\fR
2793 doesn\*(Aqt occur in our target string before actually running the pattern
2794 through. But in the second case, we\*(Aqve tricked it into thinking that our
2795 pattern is more complicated. It takes a look, sees our
2796 character class, and decides that it will have to actually run the
2797 pattern to determine whether or not it matches, and in the process of
2798 running it hits the print statement before it discovers that we don\*(Aqt
2799 have a match.
2800 .PP
2801 To take a closer look at how the engine does optimizations, see the
2802 section "Pragmas and debugging" below.
2803 .PP
2804 More fun with \f(CW\*(C`?{}\*(C'\fR:
2805 .PP
2806 .Vb 6
2807 \& $x =~ /(?{print "Hi Mom!";})/; # matches,
2808 \& # prints \*(AqHi Mom!\*(Aq
2809 \& $x =~ /(?{$c = 1;})(?{print "$c";})/; # matches,
2810 \& # prints \*(Aq1\*(Aq
2811 \& $x =~ /(?{$c = 1;})(?{print "$^R";})/; # matches,
2812 \& # prints \*(Aq1\*(Aq
2813 .Ve
2814 .PP
2815 The bit of magic mentioned in the section title occurs when the regexp
2816 backtracks in the process of searching for a match. If the regexp
2817 backtracks over a code expression and if the variables used within are
2818 localized using \f(CW\*(C`local\*(C'\fR, the changes in the variables produced by the
2819 code expression are undone! Thus, if we wanted to count how many times
2820 a character got matched inside a group, we could use, \fIe.g.\fR,
2821 .PP
2822 .Vb 11
2823 \& $x = "aaaa";
2824 \& $count = 0; # initialize \*(Aqa\*(Aq count
2825 \& $c = "bob"; # test if $c gets clobbered
2826 \& $x =~ /(?{local $c = 0;}) # initialize count
2827 \& ( a # match \*(Aqa\*(Aq
2828 \& (?{local $c = $c + 1;}) # increment count
2829 \& )* # do this any number of times,
2830 \& aa # but match \*(Aqaa\*(Aq at the end
2831 \& (?{$count = $c;}) # copy local $c var into $count
2832 \& /x;
2833 \& print "\*(Aqa\*(Aq count is $count, \e$c variable is \*(Aq$c\*(Aq\en";
2834 .Ve
2835 .PP
2836 This prints
2837 .PP
2838 .Vb 1
2839 \& \*(Aqa\*(Aq count is 2, $c variable is \*(Aqbob\*(Aq
2840 .Ve
2841 .PP
2842 If we replace the \f(CW\*(C`\ (?{local\ $c\ =\ $c\ +\ 1;})\*(C'\fR with
2843 \&\f(CW\*(C`\ (?{$c\ =\ $c\ +\ 1;})\*(C'\fR, the variable changes are \fInot\fR undone
2844 during backtracking, and we get
2845 .PP
2846 .Vb 1
2847 \& \*(Aqa\*(Aq count is 4, $c variable is \*(Aqbob\*(Aq
2848 .Ve
2849 .PP
2850 Note that only localized variable changes are undone. Other side
2851 effects of code expression execution are permanent. Thus
2852 .PP
2853 .Vb 2
2854 \& $x = "aaaa";
2855 \& $x =~ /(a(?{print "Yow\en";}))*aa/;
2856 .Ve
2857 .PP
2858 produces
2859 .PP
2860 .Vb 4
2861 \& Yow
2862 \& Yow
2863 \& Yow
2864 \& Yow
2865 .Ve
2866 .PP
2867 The result \f(CW$^R\fR is automatically localized, so that it will behave
2868 properly in the presence of backtracking.
2869 .PP
2870 This example uses a code expression in a conditional to match a
2871 definite article, either \f(CW\*(Aqthe\*(Aq\fR in English or \f(CW\*(Aqder|die|das\*(Aq\fR in
2872 German:
2873 .PP
2874 .Vb 11
2875 \& $lang = \*(AqDE\*(Aq; # use German
2876 \& ...
2877 \& $text = "das";
2878 \& print "matched\en"
2879 \& if $text =~ /(?(?{
2880 \& $lang eq \*(AqEN\*(Aq; # is the language English?
2881 \& })
2882 \& the | # if so, then match \*(Aqthe\*(Aq
2883 \& (der|die|das) # else, match \*(Aqder|die|das\*(Aq
2884 \& )
2885 \& /xi;
2886 .Ve
2887 .PP
2888 Note that the syntax here is \f(CW\*(C`(?(?{...})\fR\f(CIyes\-regexp\fR\f(CW|\fR\f(CIno\-regexp\fR\f(CW)\*(C'\fR, not
2889 \&\f(CW\*(C`(?((?{...}))\fR\f(CIyes\-regexp\fR\f(CW|\fR\f(CIno\-regexp\fR\f(CW)\*(C'\fR. In other words, in the case of a
2890 code expression, we don\*(Aqt need the extra parentheses around the
2891 conditional.
2892 .PP
2893 If you try to use code expressions where the code text is contained within
2894 an interpolated variable, rather than appearing literally in the pattern,
2895 Perl may surprise you:
2896 .PP
2897 .Vb 5
2898 \& $bar = 5;
2899 \& $pat = \*(Aq(?{ 1 })\*(Aq;
2900 \& /foo(?{ $bar })bar/; # compiles ok, $bar not interpolated
2901 \& /foo(?{ 1 })$bar/; # compiles ok, $bar interpolated
2902 \& /foo${pat}bar/; # compile error!
2903 \&
2904 \& $pat = qr/(?{ $foo = 1 })/; # precompile code regexp
2905 \& /foo${pat}bar/; # compiles ok
2906 .Ve
2907 .PP
2908 If a regexp has a variable that interpolates a code expression, Perl
2909 treats the regexp as an error. If the code expression is precompiled into
2910 a variable, however, interpolating is ok. The question is, why is this an
2911 error?
2912 .PP
2913 The reason is that variable interpolation and code expressions
2914 together pose a security risk. The combination is dangerous because
2915 many programmers who write search engines often take user input and
2916 plug it directly into a regexp:
2917 .PP
2918 .Vb 3
2919 \& $regexp = <>; # read user\-supplied regexp
2920 \& $chomp $regexp; # get rid of possible newline
2921 \& $text =~ /$regexp/; # search $text for the $regexp
2922 .Ve
2923 .PP
2924 If the \f(CW$regexp\fR variable contains a code expression, the user could
2925 then execute arbitrary Perl code. For instance, some joker could
2926 search for \f(CW\*(C`system(\*(Aqrm\ \-rf\ *\*(Aq);\*(C'\fR to erase your files. In this
2927 sense, the combination of interpolation and code expressions \fItaints\fR
2928 your regexp. So by default, using both interpolation and code
2929 expressions in the same regexp is not allowed. If you\*(Aqre not
2930 concerned about malicious users, it is possible to bypass this
2931 security check by invoking \f(CW\*(C`use\ re\ \*(Aqeval\*(Aq\*(C'\fR:
2932 .PP
2933 .Vb 4
2934 \& use re \*(Aqeval\*(Aq; # throw caution out the door
2935 \& $bar = 5;
2936 \& $pat = \*(Aq(?{ 1 })\*(Aq;
2937 \& /foo${pat}bar/; # compiles ok
2938 .Ve
2939 .PP
2940 Another form of code expression is the \fIpattern code expression\fR.
2941 The pattern code expression is like a regular code expression, except
2942 that the result of the code evaluation is treated as a regular
2943 expression and matched immediately. A simple example is
2944 .PP
2945 .Vb 4
2946 \& $length = 5;
2947 \& $char = \*(Aqa\*(Aq;
2948 \& $x = \*(Aqaaaaabb\*(Aq;
2949 \& $x =~ /(??{$char x $length})/x; # matches, there are 5 of \*(Aqa\*(Aq
2950 .Ve
2951 .PP
2952 This final example contains both ordinary and pattern code
2953 expressions. It detects whether a binary string \f(CW1101010010001...\fR has a
2954 Fibonacci spacing 0,1,1,2,3,5,... of the \f(CW\*(Aq1\*(Aq\fR\*(Aqs:
2955 .PP
2956 .Vb 12
2957 \& $x = "1101010010001000001";
2958 \& $z0 = \*(Aq\*(Aq; $z1 = \*(Aq0\*(Aq; # initial conditions
2959 \& print "It is a Fibonacci sequence\en"
2960 \& if $x =~ /^1 # match an initial \*(Aq1\*(Aq
2961 \& (?:
2962 \& ((??{ $z0 })) # match some \*(Aq0\*(Aq
2963 \& 1 # and then a \*(Aq1\*(Aq
2964 \& (?{ $z0 = $z1; $z1 .= $^N; })
2965 \& )+ # repeat as needed
2966 \& $ # that is all there is
2967 \& /x;
2968 \& printf "Largest sequence matched was %d\en", length($z1)\-length($z0);
2969 .Ve
2970 .PP
2971 Remember that \f(CW$^N\fR is set to whatever was matched by the last
2972 completed capture group. This prints
2973 .PP
2974 .Vb 2
2975 \& It is a Fibonacci sequence
2976 \& Largest sequence matched was 5
2977 .Ve
2978 .PP
2979 Ha! Try that with your garden variety regexp package...
2980 .PP
2981 Note that the variables \f(CW$z0\fR and \f(CW$z1\fR are not substituted when the
2982 regexp is compiled, as happens for ordinary variables outside a code
2983 expression. Rather, the whole code block is parsed as perl code at the
2984 same time as perl is compiling the code containing the literal regexp
2985 pattern.
2986 .PP
2987 This regexp without the \f(CW\*(C`/x\*(C'\fR modifier is
2988 .PP
2989 .Vb 1
2990 \& /^1(?:((??{ $z0 }))1(?{ $z0 = $z1; $z1 .= $^N; }))+$/
2991 .Ve
2992 .PP
2993 which shows that spaces are still possible in the code parts. Nevertheless,
2994 when working with code and conditional expressions, the extended form of
2995 regexps is almost necessary in creating and debugging regexps.
2996 .SS "Backtracking control verbs"
2997 .IX Subsection "Backtracking control verbs"
2998 Perl 5.10 introduced a number of control verbs intended to provide
2999 detailed control over the backtracking process, by directly influencing
3000 the regexp engine and by providing monitoring techniques. See
3001 "Special Backtracking Control Verbs" in perlre for a detailed
3002 description.
3003 .PP
3004 Below is just one example, illustrating the control verb \f(CW\*(C`(*FAIL)\*(C'\fR,
3005 which may be abbreviated as \f(CW\*(C`(*F)\*(C'\fR. If this is inserted in a regexp
3006 it will cause it to fail, just as it would at some
3007 mismatch between the pattern and the string. Processing
3008 of the regexp continues as it would after any "normal"
3009 failure, so that, for instance, the next position in the string or another
3010 alternative will be tried. As failing to match doesn\*(Aqt preserve capture
3011 groups or produce results, it may be necessary to use this in
3012 combination with embedded code.
3013 .PP
3014 .Vb 4
3015 \& my %count;
3016 \& "supercalifragilisticexpialidocious" =~
3017 \& /([aeiou])(?{ $count{lc($1)}++; })(*FAIL)/i;
3018 \& printf "%3d \*(Aq%s\*(Aq\en", $count{$_}, $_ for (sort keys %count);
3019 .Ve
3020 .PP
3021 The pattern begins with a class matching a subset of letters. Whenever
3022 this matches, a statement like \f(CW\*(C`$count{\*(Aqa\*(Aq}++;\*(C'\fR is executed, incrementing
3023 the letter\*(Aqs counter. Then \f(CW\*(C`(*FAIL)\*(C'\fR does what it says, and
3024 the regexp engine proceeds according to the book: as long as the end of
3025 the string hasn\*(Aqt been reached, the position is advanced before looking
3026 for another vowel. Thus, match or no match makes no difference, and the
3027 regexp engine proceeds until the entire string has been inspected.
3028 .PP
3029 (In a real program, you might instead solve this problem using
3030 .PP
3031 .Vb 4
3032 \& my $string = "supercalifragilisticexpialidocious";
3033 \& my %count;
3034 \& $count{lc($1)}++ while $string =~ /([aeiou])/ig;
3035 \& printf "%3d \*(Aq%s\*(Aq\en", $count{$_}, $_ for (sort keys %count);
3036 .Ve
3037 .PP
3038 This is faster than embedded code blocks in the regex.)
3039 .SS "Pragmas and debugging"
3040 .IX Subsection "Pragmas and debugging"
3041 Speaking of debugging, there are several pragmas available to control
3042 and debug regexps in Perl. We have already encountered one pragma in
3043 the previous section, \f(CW\*(C`use\ re\ \*(Aqeval\*(Aq;\*(C'\fR, that allows variable
3044 interpolation and code expressions to coexist in a regexp. The other
3045 pragmas are
3046 .PP
3047 .Vb 3
3048 \& use re \*(Aqtaint\*(Aq;
3049 \& $tainted = <>;
3050 \& @parts = ($tainted =~ /(\ew+)\es+(\ew+)/; # @parts is now tainted
3051 .Ve
3052 .PP
3053 The \f(CW\*(C`taint\*(C'\fR pragma causes any substrings from a match with a tainted
3054 variable to be tainted as well, if your perl supports tainting
3055 (see perlsec). This is not normally the case, as
3056 regexps are often used to extract the safe bits from a tainted
3057 variable. Use \f(CW\*(C`taint\*(C'\fR when you are not extracting safe bits, but are
3058 performing some other processing. Both \f(CW\*(C`taint\*(C'\fR and \f(CW\*(C`eval\*(C'\fR pragmas
3059 are lexically scoped, which means they are in effect only until
3060 the end of the block enclosing the pragmas.
3061 .PP
3062 .Vb 2
3063 \& use re \*(Aq/m\*(Aq; # or any other flags
3064 \& $multiline_string =~ /^foo/; # /m is implied
3065 .Ve
3066 .PP
3067 The \f(CW\*(C`re \*(Aq/flags\*(Aq\*(C'\fR pragma (introduced in Perl
3068 5.14) turns on the given regular expression flags
3069 until the end of the lexical scope. See
3070 "\*(Aq/flags\*(Aq mode" in re for more
3071 detail.
3072 .PP
3073 .Vb 2
3074 \& use re \*(Aqdebug\*(Aq;
3075 \& /^(.*)$/s; # output debugging info
3076 \&
3077 \& use re \*(Aqdebugcolor\*(Aq;
3078 \& /^(.*)$/s; # output debugging info in living color
3079 .Ve
3080 .PP
3081 The global \f(CW\*(C`debug\*(C'\fR and \f(CW\*(C`debugcolor\*(C'\fR pragmas allow one to get
3082 detailed debugging info about regexp compilation and
3083 execution. \f(CW\*(C`debugcolor\*(C'\fR is the same as debug, except the debugging
3084 information is displayed in color on terminals that can display
3085 termcap color sequences. Here is example output:
3086 .PP
3087 .Vb 10
3088 \& % perl \-e \*(Aquse re "debug"; "abc" =~ /a*b+c/;\*(Aq
3089 \& Compiling REx \*(Aqa*b+c\*(Aq
3090 \& size 9 first at 1
3091 \& 1: STAR(4)
3092 \& 2: EXACT <a>(0)
3093 \& 4: PLUS(7)
3094 \& 5: EXACT <b>(0)
3095 \& 7: EXACT <c>(9)
3096 \& 9: END(0)
3097 \& floating \*(Aqbc\*(Aq at 0..2147483647 (checking floating) minlen 2
3098 \& Guessing start of match, REx \*(Aqa*b+c\*(Aq against \*(Aqabc\*(Aq...
3099 \& Found floating substr \*(Aqbc\*(Aq at offset 1...
3100 \& Guessed: match at offset 0
3101 \& Matching REx \*(Aqa*b+c\*(Aq against \*(Aqabc\*(Aq
3102 \& Setting an EVAL scope, savestack=3
3103 \& 0 <> <abc> | 1: STAR
3104 \& EXACT <a> can match 1 times out of 32767...
3105 \& Setting an EVAL scope, savestack=3
3106 \& 1 <a> <bc> | 4: PLUS
3107 \& EXACT <b> can match 1 times out of 32767...
3108 \& Setting an EVAL scope, savestack=3
3109 \& 2 <ab> <c> | 7: EXACT <c>
3110 \& 3 <abc> <> | 9: END
3111 \& Match successful!
3112 \& Freeing REx: \*(Aqa*b+c\*(Aq
3113 .Ve
3114 .PP
3115 If you have gotten this far into the tutorial, you can probably guess
3116 what the different parts of the debugging output tell you. The first
3117 part
3118 .PP
3119 .Vb 8
3120 \& Compiling REx \*(Aqa*b+c\*(Aq
3121 \& size 9 first at 1
3122 \& 1: STAR(4)
3123 \& 2: EXACT <a>(0)
3124 \& 4: PLUS(7)
3125 \& 5: EXACT <b>(0)
3126 \& 7: EXACT <c>(9)
3127 \& 9: END(0)
3128 .Ve
3129 .PP
3130 describes the compilation stage. \f(CWSTAR(4)\fR means that there is a
3131 starred object, in this case \f(CW\*(Aqa\*(Aq\fR, and if it matches, goto line 4,
3132 \&\fIi.e.\fR, \f(CWPLUS(7)\fR. The middle lines describe some heuristics and
3133 optimizations performed before a match:
3134 .PP
3135 .Vb 4
3136 \& floating \*(Aqbc\*(Aq at 0..2147483647 (checking floating) minlen 2
3137 \& Guessing start of match, REx \*(Aqa*b+c\*(Aq against \*(Aqabc\*(Aq...
3138 \& Found floating substr \*(Aqbc\*(Aq at offset 1...
3139 \& Guessed: match at offset 0
3140 .Ve
3141 .PP
3142 Then the match is executed and the remaining lines describe the
3143 process:
3144 .PP
3145 .Vb 12
3146 \& Matching REx \*(Aqa*b+c\*(Aq against \*(Aqabc\*(Aq
3147 \& Setting an EVAL scope, savestack=3
3148 \& 0 <> <abc> | 1: STAR
3149 \& EXACT <a> can match 1 times out of 32767...
3150 \& Setting an EVAL scope, savestack=3
3151 \& 1 <a> <bc> | 4: PLUS
3152 \& EXACT <b> can match 1 times out of 32767...
3153 \& Setting an EVAL scope, savestack=3
3154 \& 2 <ab> <c> | 7: EXACT <c>
3155 \& 3 <abc> <> | 9: END
3156 \& Match successful!
3157 \& Freeing REx: \*(Aqa*b+c\*(Aq
3158 .Ve
3159 .PP
3160 Each step is of the form \f(CW\*(C`n\ <x>\ <y>\*(C'\fR, with \f(CW\*(C`<x>\*(C'\fR the
3161 part of the string matched and \f(CW\*(C`<y>\*(C'\fR the part not yet
3162 matched. The \f(CW\*(C`|\ \ 1:\ \ STAR\*(C'\fR says that Perl is at line number 1
3163 in the compilation list above. See
3164 "Debugging Regular Expressions" in perldebguts for much more detail.
3165 .PP
3166 An alternative method of debugging regexps is to embed \f(CW\*(C`print\*(C'\fR
3167 statements within the regexp. This provides a blow\-by\-blow account of
3168 the backtracking in an alternation:
3169 .PP
3170 .Vb 12
3171 \& "that this" =~ m@(?{print "Start at position ", pos, "\en";})
3172 \& t(?{print "t1\en";})
3173 \& h(?{print "h1\en";})
3174 \& i(?{print "i1\en";})
3175 \& s(?{print "s1\en";})
3176 \& |
3177 \& t(?{print "t2\en";})
3178 \& h(?{print "h2\en";})
3179 \& a(?{print "a2\en";})
3180 \& t(?{print "t2\en";})
3181 \& (?{print "Done at position ", pos, "\en";})
3182 \& @x;
3183 .Ve
3184 .PP
3185 prints
3186 .PP
3187 .Vb 8
3188 \& Start at position 0
3189 \& t1
3190 \& h1
3191 \& t2
3192 \& h2
3193 \& a2
3194 \& t2
3195 \& Done at position 4
3196 .Ve
3197 .SH "SEE ALSO"
3198 .IX Header "SEE ALSO"
3199 This is just a tutorial. For the full story on Perl regular
3200 expressions, see the perlre regular expressions reference page.
3201 .PP
3202 For more information on the matching \f(CW\*(C`m//\*(C'\fR and substitution \f(CW\*(C`s///\*(C'\fR
3203 operators, see "Regexp Quote\-Like Operators" in perlop. For
3204 information on the \f(CW\*(C`split\*(C'\fR operation, see "split" in perlfunc.
3205 .PP
3206 For an excellent all\-around resource on the care and feeding of
3207 regular expressions, see the book \fIMastering Regular Expressions\fR by
3208 Jeffrey Friedl (published by O\*(AqReilly, ISBN 1556592\-257\-3).
3209 .SH "AUTHOR AND COPYRIGHT"
3210 .IX Header "AUTHOR AND COPYRIGHT"
3211 Copyright (c) 2000 Mark Kvale.
3212 All rights reserved.
3213 Now maintained by Perl porters.
3214 .PP
3215 This document may be distributed under the same terms as Perl itself.
3216 .SS Acknowledgments
3217 .IX Subsection "Acknowledgments"
3218 The inspiration for the stop codon DNA example came from the ZIP
3219 code example in chapter 7 of \fIMastering Regular Expressions\fR.
3220 .PP
3221 The author would like to thank Jeff Pinyan, Andrew Johnson, Peter
3222 Haworth, Ronald J Kimball, and Joe Smith for all their helpful
3223 comments.