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