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