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