Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2504 lines
100 KiB

  1. =head1 NAME
  2. perlretut - Perl regular expressions tutorial
  3. =head1 DESCRIPTION
  4. This page provides a basic tutorial on understanding, creating and
  5. using regular expressions in Perl. It serves as a complement to the
  6. reference page on regular expressions L<perlre>. Regular expressions
  7. are an integral part of the C<m//>, C<s///>, C<qr//> and C<split>
  8. operators and so this tutorial also overlaps with
  9. L<perlop/"Regexp Quote-Like Operators"> and L<perlfunc/split>.
  10. Perl is widely renowned for excellence in text processing, and regular
  11. expressions are one of the big factors behind this fame. Perl regular
  12. expressions display an efficiency and flexibility unknown in most
  13. other computer languages. Mastering even the basics of regular
  14. expressions will allow you to manipulate text with surprising ease.
  15. What is a regular expression? A regular expression is simply a string
  16. that describes a pattern. Patterns are in common use these days;
  17. examples are the patterns typed into a search engine to find web pages
  18. and the patterns used to list files in a directory, e.g., C<ls *.txt>
  19. or C<dir *.*>. In Perl, the patterns described by regular expressions
  20. are used to search strings, extract desired parts of strings, and to
  21. do search and replace operations.
  22. Regular expressions have the undeserved reputation of being abstract
  23. and difficult to understand. Regular expressions are constructed using
  24. simple concepts like conditionals and loops and are no more difficult
  25. to understand than the corresponding C<if> conditionals and C<while>
  26. loops in the Perl language itself. In fact, the main challenge in
  27. learning regular expressions is just getting used to the terse
  28. notation used to express these concepts.
  29. This tutorial flattens the learning curve by discussing regular
  30. expression concepts, along with their notation, one at a time and with
  31. many examples. The first part of the tutorial will progress from the
  32. simplest word searches to the basic regular expression concepts. If
  33. you master the first part, you will have all the tools needed to solve
  34. about 98% of your needs. The second part of the tutorial is for those
  35. comfortable with the basics and hungry for more power tools. It
  36. discusses the more advanced regular expression operators and
  37. introduces the latest cutting edge innovations in 5.6.0.
  38. A note: to save time, 'regular expression' is often abbreviated as
  39. regexp or regex. Regexp is a more natural abbreviation than regex, but
  40. is harder to pronounce. The Perl pod documentation is evenly split on
  41. regexp vs regex; in Perl, there is more than one way to abbreviate it.
  42. We'll use regexp in this tutorial.
  43. =head1 Part 1: The basics
  44. =head2 Simple word matching
  45. The simplest regexp is simply a word, or more generally, a string of
  46. characters. A regexp consisting of a word matches any string that
  47. contains that word:
  48. "Hello World" =~ /World/; # matches
  49. What is this perl statement all about? C<"Hello World"> is a simple
  50. double quoted string. C<World> is the regular expression and the
  51. C<//> enclosing C</World/> tells perl to search a string for a match.
  52. The operator C<=~> associates the string with the regexp match and
  53. produces a true value if the regexp matched, or false if the regexp
  54. did not match. In our case, C<World> matches the second word in
  55. C<"Hello World">, so the expression is true. Expressions like this
  56. are useful in conditionals:
  57. if ("Hello World" =~ /World/) {
  58. print "It matches\n";
  59. }
  60. else {
  61. print "It doesn't match\n";
  62. }
  63. There are useful variations on this theme. The sense of the match can
  64. be reversed by using C<!~> operator:
  65. if ("Hello World" !~ /World/) {
  66. print "It doesn't match\n";
  67. }
  68. else {
  69. print "It matches\n";
  70. }
  71. The literal string in the regexp can be replaced by a variable:
  72. $greeting = "World";
  73. if ("Hello World" =~ /$greeting/) {
  74. print "It matches\n";
  75. }
  76. else {
  77. print "It doesn't match\n";
  78. }
  79. If you're matching against the special default variable C<$_>, the
  80. C<$_ =~> part can be omitted:
  81. $_ = "Hello World";
  82. if (/World/) {
  83. print "It matches\n";
  84. }
  85. else {
  86. print "It doesn't match\n";
  87. }
  88. And finally, the C<//> default delimiters for a match can be changed
  89. to arbitrary delimiters by putting an C<'m'> out front:
  90. "Hello World" =~ m!World!; # matches, delimited by '!'
  91. "Hello World" =~ m{World}; # matches, note the matching '{}'
  92. "/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin',
  93. # '/' becomes an ordinary char
  94. C</World/>, C<m!World!>, and C<m{World}> all represent the
  95. same thing. When, e.g., C<""> is used as a delimiter, the forward
  96. slash C<'/'> becomes an ordinary character and can be used in a regexp
  97. without trouble.
  98. Let's consider how different regexps would match C<"Hello World">:
  99. "Hello World" =~ /world/; # doesn't match
  100. "Hello World" =~ /o W/; # matches
  101. "Hello World" =~ /oW/; # doesn't match
  102. "Hello World" =~ /World /; # doesn't match
  103. The first regexp C<world> doesn't match because regexps are
  104. case-sensitive. The second regexp matches because the substring
  105. S<C<'o W'> > occurs in the string S<C<"Hello World"> >. The space
  106. character ' ' is treated like any other character in a regexp and is
  107. needed to match in this case. The lack of a space character is the
  108. reason the third regexp C<'oW'> doesn't match. The fourth regexp
  109. C<'World '> doesn't match because there is a space at the end of the
  110. regexp, but not at the end of the string. The lesson here is that
  111. regexps must match a part of the string I<exactly> in order for the
  112. statement to be true.
  113. If a regexp matches in more than one place in the string, perl will
  114. always match at the earliest possible point in the string:
  115. "Hello World" =~ /o/; # matches 'o' in 'Hello'
  116. "That hat is red" =~ /hat/; # matches 'hat' in 'That'
  117. With respect to character matching, there are a few more points you
  118. need to know about. First of all, not all characters can be used 'as
  119. is' in a match. Some characters, called B<metacharacters>, are reserved
  120. for use in regexp notation. The metacharacters are
  121. {}[]()^$.|*+?\
  122. The significance of each of these will be explained
  123. in the rest of the tutorial, but for now, it is important only to know
  124. that a metacharacter can be matched by putting a backslash before it:
  125. "2+2=4" =~ /2+2/; # doesn't match, + is a metacharacter
  126. "2+2=4" =~ /2\+2/; # matches, \+ is treated like an ordinary +
  127. "The interval is [0,1)." =~ /[0,1)./ # is a syntax error!
  128. "The interval is [0,1)." =~ /\[0,1\)\./ # matches
  129. "/usr/bin/perl" =~ /\/usr\/local\/bin\/perl/; # matches
  130. In the last regexp, the forward slash C<'/'> is also backslashed,
  131. because it is used to delimit the regexp. This can lead to LTS
  132. (leaning toothpick syndrome), however, and it is often more readable
  133. to change delimiters.
  134. The backslash character C<'\'> is a metacharacter itself and needs to
  135. be backslashed:
  136. 'C:\WIN32' =~ /C:\\WIN/; # matches
  137. In addition to the metacharacters, there are some ASCII characters
  138. which don't have printable character equivalents and are instead
  139. represented by B<escape sequences>. Common examples are C<\t> for a
  140. tab, C<\n> for a newline, C<\r> for a carriage return and C<\a> for a
  141. bell. If your string is better thought of as a sequence of arbitrary
  142. bytes, the octal escape sequence, e.g., C<\033>, or hexadecimal escape
  143. sequence, e.g., C<\x1B> may be a more natural representation for your
  144. bytes. Here are some examples of escapes:
  145. "1000\t2000" =~ m(0\t2) # matches
  146. "1000\n2000" =~ /0\n20/ # matches
  147. "1000\t2000" =~ /\000\t2/ # doesn't match, "0" ne "\000"
  148. "cat" =~ /\143\x61\x74/ # matches, but a weird way to spell cat
  149. If you've been around Perl a while, all this talk of escape sequences
  150. may seem familiar. Similar escape sequences are used in double-quoted
  151. strings and in fact the regexps in Perl are mostly treated as
  152. double-quoted strings. This means that variables can be used in
  153. regexps as well. Just like double-quoted strings, the values of the
  154. variables in the regexp will be substituted in before the regexp is
  155. evaluated for matching purposes. So we have:
  156. $foo = 'house';
  157. 'housecat' =~ /$foo/; # matches
  158. 'cathouse' =~ /cat$foo/; # matches
  159. 'housecat' =~ /${foo}cat/; # matches
  160. So far, so good. With the knowledge above you can already perform
  161. searches with just about any literal string regexp you can dream up.
  162. Here is a I<very simple> emulation of the Unix grep program:
  163. % cat > simple_grep
  164. #!/usr/bin/perl
  165. $regexp = shift;
  166. while (<>) {
  167. print if /$regexp/;
  168. }
  169. ^D
  170. % chmod +x simple_grep
  171. % simple_grep abba /usr/dict/words
  172. Babbage
  173. cabbage
  174. cabbages
  175. sabbath
  176. Sabbathize
  177. Sabbathizes
  178. sabbatical
  179. scabbard
  180. scabbards
  181. This program is easy to understand. C<#!/usr/bin/perl> is the standard
  182. way to invoke a perl program from the shell.
  183. S<C<$regexp = shift;> > saves the first command line argument as the
  184. regexp to be used, leaving the rest of the command line arguments to
  185. be treated as files. S<C<< while (<>) >> > loops over all the lines in
  186. all the files. For each line, S<C<print if /$regexp/;> > prints the
  187. line if the regexp matches the line. In this line, both C<print> and
  188. C</$regexp/> use the default variable C<$_> implicitly.
  189. With all of the regexps above, if the regexp matched anywhere in the
  190. string, it was considered a match. Sometimes, however, we'd like to
  191. specify I<where> in the string the regexp should try to match. To do
  192. this, we would use the B<anchor> metacharacters C<^> and C<$>. The
  193. anchor C<^> means match at the beginning of the string and the anchor
  194. C<$> means match at the end of the string, or before a newline at the
  195. end of the string. Here is how they are used:
  196. "housekeeper" =~ /keeper/; # matches
  197. "housekeeper" =~ /^keeper/; # doesn't match
  198. "housekeeper" =~ /keeper$/; # matches
  199. "housekeeper\n" =~ /keeper$/; # matches
  200. The second regexp doesn't match because C<^> constrains C<keeper> to
  201. match only at the beginning of the string, but C<"housekeeper"> has
  202. keeper starting in the middle. The third regexp does match, since the
  203. C<$> constrains C<keeper> to match only at the end of the string.
  204. When both C<^> and C<$> are used at the same time, the regexp has to
  205. match both the beginning and the end of the string, i.e., the regexp
  206. matches the whole string. Consider
  207. "keeper" =~ /^keep$/; # doesn't match
  208. "keeper" =~ /^keeper$/; # matches
  209. "" =~ /^$/; # ^$ matches an empty string
  210. The first regexp doesn't match because the string has more to it than
  211. C<keep>. Since the second regexp is exactly the string, it
  212. matches. Using both C<^> and C<$> in a regexp forces the complete
  213. string to match, so it gives you complete control over which strings
  214. match and which don't. Suppose you are looking for a fellow named
  215. bert, off in a string by himself:
  216. "dogbert" =~ /bert/; # matches, but not what you want
  217. "dilbert" =~ /^bert/; # doesn't match, but ..
  218. "bertram" =~ /^bert/; # matches, so still not good enough
  219. "bertram" =~ /^bert$/; # doesn't match, good
  220. "dilbert" =~ /^bert$/; # doesn't match, good
  221. "bert" =~ /^bert$/; # matches, perfect
  222. Of course, in the case of a literal string, one could just as easily
  223. use the string equivalence S<C<$string eq 'bert'> > and it would be
  224. more efficient. The C<^...$> regexp really becomes useful when we
  225. add in the more powerful regexp tools below.
  226. =head2 Using character classes
  227. Although one can already do quite a lot with the literal string
  228. regexps above, we've only scratched the surface of regular expression
  229. technology. In this and subsequent sections we will introduce regexp
  230. concepts (and associated metacharacter notations) that will allow a
  231. regexp to not just represent a single character sequence, but a I<whole
  232. class> of them.
  233. One such concept is that of a B<character class>. A character class
  234. allows a set of possible characters, rather than just a single
  235. character, to match at a particular point in a regexp. Character
  236. classes are denoted by brackets C<[...]>, with the set of characters
  237. to be possibly matched inside. Here are some examples:
  238. /cat/; # matches 'cat'
  239. /[bcr]at/; # matches 'bat, 'cat', or 'rat'
  240. /item[0123456789]/; # matches 'item0' or ... or 'item9'
  241. "abc" =~ /[cab]/; # matches 'a'
  242. In the last statement, even though C<'c'> is the first character in
  243. the class, C<'a'> matches because the first character position in the
  244. string is the earliest point at which the regexp can match.
  245. /[yY][eE][sS]/; # match 'yes' in a case-insensitive way
  246. # 'yes', 'Yes', 'YES', etc.
  247. This regexp displays a common task: perform a a case-insensitive
  248. match. Perl provides away of avoiding all those brackets by simply
  249. appending an C<'i'> to the end of the match. Then C</[yY][eE][sS]/;>
  250. can be rewritten as C</yes/i;>. The C<'i'> stands for
  251. case-insensitive and is an example of a B<modifier> of the matching
  252. operation. We will meet other modifiers later in the tutorial.
  253. We saw in the section above that there were ordinary characters, which
  254. represented themselves, and special characters, which needed a
  255. backslash C<\> to represent themselves. The same is true in a
  256. character class, but the sets of ordinary and special characters
  257. inside a character class are different than those outside a character
  258. class. The special characters for a character class are C<-]\^$>. C<]>
  259. is special because it denotes the end of a character class. C<$> is
  260. special because it denotes a scalar variable. C<\> is special because
  261. it is used in escape sequences, just like above. Here is how the
  262. special characters C<]$\> are handled:
  263. /[\]c]def/; # matches ']def' or 'cdef'
  264. $x = 'bcr';
  265. /[$x]at/; # matches 'bat', 'cat', or 'rat'
  266. /[\$x]at/; # matches '$at' or 'xat'
  267. /[\\$x]at/; # matches '\at', 'bat, 'cat', or 'rat'
  268. The last two are a little tricky. in C<[\$x]>, the backslash protects
  269. the dollar sign, so the character class has two members C<$> and C<x>.
  270. In C<[\\$x]>, the backslash is protected, so C<$x> is treated as a
  271. variable and substituted in double quote fashion.
  272. The special character C<'-'> acts as a range operator within character
  273. classes, so that a contiguous set of characters can be written as a
  274. range. With ranges, the unwieldy C<[0123456789]> and C<[abc...xyz]>
  275. become the svelte C<[0-9]> and C<[a-z]>. Some examples are
  276. /item[0-9]/; # matches 'item0' or ... or 'item9'
  277. /[0-9bx-z]aa/; # matches '0aa', ..., '9aa',
  278. # 'baa', 'xaa', 'yaa', or 'zaa'
  279. /[0-9a-fA-F]/; # matches a hexadecimal digit
  280. /[0-9a-zA-Z_]/; # matches a "word" character,
  281. # like those in a perl variable name
  282. If C<'-'> is the first or last character in a character class, it is
  283. treated as an ordinary character; C<[-ab]>, C<[ab-]> and C<[a\-b]> are
  284. all equivalent.
  285. The special character C<^> in the first position of a character class
  286. denotes a B<negated character class>, which matches any character but
  287. those in the brackets. Both C<[...]> and C<[^...]> must match a
  288. character, or the match fails. Then
  289. /[^a]at/; # doesn't match 'aat' or 'at', but matches
  290. # all other 'bat', 'cat, '0at', '%at', etc.
  291. /[^0-9]/; # matches a non-numeric character
  292. /[a^]at/; # matches 'aat' or '^at'; here '^' is ordinary
  293. Now, even C<[0-9]> can be a bother the write multiple times, so in the
  294. interest of saving keystrokes and making regexps more readable, Perl
  295. has several abbreviations for common character classes:
  296. =over 4
  297. =item *
  298. \d is a digit and represents [0-9]
  299. =item *
  300. \s is a whitespace character and represents [\ \t\r\n\f]
  301. =item *
  302. \w is a word character (alphanumeric or _) and represents [0-9a-zA-Z_]
  303. =item *
  304. \D is a negated \d; it represents any character but a digit [^0-9]
  305. =item *
  306. \S is a negated \s; it represents any non-whitespace character [^\s]
  307. =item *
  308. \W is a negated \w; it represents any non-word character [^\w]
  309. =item *
  310. The period '.' matches any character but "\n"
  311. =back
  312. The C<\d\s\w\D\S\W> abbreviations can be used both inside and outside
  313. of character classes. Here are some in use:
  314. /\d\d:\d\d:\d\d/; # matches a hh:mm:ss time format
  315. /[\d\s]/; # matches any digit or whitespace character
  316. /\w\W\w/; # matches a word char, followed by a
  317. # non-word char, followed by a word char
  318. /..rt/; # matches any two chars, followed by 'rt'
  319. /end\./; # matches 'end.'
  320. /end[.]/; # same thing, matches 'end.'
  321. Because a period is a metacharacter, it needs to be escaped to match
  322. as an ordinary period. Because, for example, C<\d> and C<\w> are sets
  323. of characters, it is incorrect to think of C<[^\d\w]> as C<[\D\W]>; in
  324. fact C<[^\d\w]> is the same as C<[^\w]>, which is the same as
  325. C<[\W]>. Think DeMorgan's laws.
  326. An anchor useful in basic regexps is the S<B<word anchor> >
  327. C<\b>. This matches a boundary between a word character and a non-word
  328. character C<\w\W> or C<\W\w>:
  329. $x = "Housecat catenates house and cat";
  330. $x =~ /cat/; # matches cat in 'housecat'
  331. $x =~ /\bcat/; # matches cat in 'catenates'
  332. $x =~ /cat\b/; # matches cat in 'housecat'
  333. $x =~ /\bcat\b/; # matches 'cat' at end of string
  334. Note in the last example, the end of the string is considered a word
  335. boundary.
  336. You might wonder why C<'.'> matches everything but C<"\n"> - why not
  337. every character? The reason is that often one is matching against
  338. lines and would like to ignore the newline characters. For instance,
  339. while the string C<"\n"> represents one line, we would like to think
  340. of as empty. Then
  341. "" =~ /^$/; # matches
  342. "\n" =~ /^$/; # matches, "\n" is ignored
  343. "" =~ /./; # doesn't match; it needs a char
  344. "" =~ /^.$/; # doesn't match; it needs a char
  345. "\n" =~ /^.$/; # doesn't match; it needs a char other than "\n"
  346. "a" =~ /^.$/; # matches
  347. "a\n" =~ /^.$/; # matches, ignores the "\n"
  348. This behavior is convenient, because we usually want to ignore
  349. newlines when we count and match characters in a line. Sometimes,
  350. however, we want to keep track of newlines. We might even want C<^>
  351. and C<$> to anchor at the beginning and end of lines within the
  352. string, rather than just the beginning and end of the string. Perl
  353. allows us to choose between ignoring and paying attention to newlines
  354. by using the C<//s> and C<//m> modifiers. C<//s> and C<//m> stand for
  355. single line and multi-line and they determine whether a string is to
  356. be treated as one continuous string, or as a set of lines. The two
  357. modifiers affect two aspects of how the regexp is interpreted: 1) how
  358. the C<'.'> character class is defined, and 2) where the anchors C<^>
  359. and C<$> are able to match. Here are the four possible combinations:
  360. =over 4
  361. =item *
  362. no modifiers (//): Default behavior. C<'.'> matches any character
  363. except C<"\n">. C<^> matches only at the beginning of the string and
  364. C<$> matches only at the end or before a newline at the end.
  365. =item *
  366. s modifier (//s): Treat string as a single long line. C<'.'> matches
  367. any character, even C<"\n">. C<^> matches only at the beginning of
  368. the string and C<$> matches only at the end or before a newline at the
  369. end.
  370. =item *
  371. m modifier (//m): Treat string as a set of multiple lines. C<'.'>
  372. matches any character except C<"\n">. C<^> and C<$> are able to match
  373. at the start or end of I<any> line within the string.
  374. =item *
  375. both s and m modifiers (//sm): Treat string as a single long line, but
  376. detect multiple lines. C<'.'> matches any character, even
  377. C<"\n">. C<^> and C<$>, however, are able to match at the start or end
  378. of I<any> line within the string.
  379. =back
  380. Here are examples of C<//s> and C<//m> in action:
  381. $x = "There once was a girl\nWho programmed in Perl\n";
  382. $x =~ /^Who/; # doesn't match, "Who" not at start of string
  383. $x =~ /^Who/s; # doesn't match, "Who" not at start of string
  384. $x =~ /^Who/m; # matches, "Who" at start of second line
  385. $x =~ /^Who/sm; # matches, "Who" at start of second line
  386. $x =~ /girl.Who/; # doesn't match, "." doesn't match "\n"
  387. $x =~ /girl.Who/s; # matches, "." matches "\n"
  388. $x =~ /girl.Who/m; # doesn't match, "." doesn't match "\n"
  389. $x =~ /girl.Who/sm; # matches, "." matches "\n"
  390. Most of the time, the default behavior is what is want, but C<//s> and
  391. C<//m> are occasionally very useful. If C<//m> is being used, the start
  392. of the string can still be matched with C<\A> and the end of string
  393. can still be matched with the anchors C<\Z> (matches both the end and
  394. the newline before, like C<$>), and C<\z> (matches only the end):
  395. $x =~ /^Who/m; # matches, "Who" at start of second line
  396. $x =~ /\AWho/m; # doesn't match, "Who" is not at start of string
  397. $x =~ /girl$/m; # matches, "girl" at end of first line
  398. $x =~ /girl\Z/m; # doesn't match, "girl" is not at end of string
  399. $x =~ /Perl\Z/m; # matches, "Perl" is at newline before end
  400. $x =~ /Perl\z/m; # doesn't match, "Perl" is not at end of string
  401. We now know how to create choices among classes of characters in a
  402. regexp. What about choices among words or character strings? Such
  403. choices are described in the next section.
  404. =head2 Matching this or that
  405. Sometimes we would like to our regexp to be able to match different
  406. possible words or character strings. This is accomplished by using
  407. the B<alternation> metacharacter C<|>. To match C<dog> or C<cat>, we
  408. form the regexp C<dog|cat>. As before, perl will try to match the
  409. regexp at the earliest possible point in the string. At each
  410. character position, perl will first try to match the first
  411. alternative, C<dog>. If C<dog> doesn't match, perl will then try the
  412. next alternative, C<cat>. If C<cat> doesn't match either, then the
  413. match fails and perl moves to the next position in the string. Some
  414. examples:
  415. "cats and dogs" =~ /cat|dog|bird/; # matches "cat"
  416. "cats and dogs" =~ /dog|cat|bird/; # matches "cat"
  417. Even though C<dog> is the first alternative in the second regexp,
  418. C<cat> is able to match earlier in the string.
  419. "cats" =~ /c|ca|cat|cats/; # matches "c"
  420. "cats" =~ /cats|cat|ca|c/; # matches "cats"
  421. Here, all the alternatives match at the first string position, so the
  422. first alternative is the one that matches. If some of the
  423. alternatives are truncations of the others, put the longest ones first
  424. to give them a chance to match.
  425. "cab" =~ /a|b|c/ # matches "c"
  426. # /a|b|c/ == /[abc]/
  427. The last example points out that character classes are like
  428. alternations of characters. At a given character position, the first
  429. alternative that allows the regexp match to succeed wil be the one
  430. that matches.
  431. =head2 Grouping things and hierarchical matching
  432. Alternation allows a regexp to choose among alternatives, but by
  433. itself it unsatisfying. The reason is that each alternative is a whole
  434. regexp, but sometime we want alternatives for just part of a
  435. regexp. For instance, suppose we want to search for housecats or
  436. housekeepers. The regexp C<housecat|housekeeper> fits the bill, but is
  437. inefficient because we had to type C<house> twice. It would be nice to
  438. have parts of the regexp be constant, like C<house>, and and some
  439. parts have alternatives, like C<cat|keeper>.
  440. The B<grouping> metacharacters C<()> solve this problem. Grouping
  441. allows parts of a regexp to be treated as a single unit. Parts of a
  442. regexp are grouped by enclosing them in parentheses. Thus we could solve
  443. the C<housecat|housekeeper> by forming the regexp as
  444. C<house(cat|keeper)>. The regexp C<house(cat|keeper)> means match
  445. C<house> followed by either C<cat> or C<keeper>. Some more examples
  446. are
  447. /(a|b)b/; # matches 'ab' or 'bb'
  448. /(ac|b)b/; # matches 'acb' or 'bb'
  449. /(^a|b)c/; # matches 'ac' at start of string or 'bc' anywhere
  450. /(a|[bc])d/; # matches 'ad', 'bd', or 'cd'
  451. /house(cat|)/; # matches either 'housecat' or 'house'
  452. /house(cat(s|)|)/; # matches either 'housecats' or 'housecat' or
  453. # 'house'. Note groups can be nested.
  454. /(19|20|)\d\d/; # match years 19xx, 20xx, or the Y2K problem, xx
  455. "20" =~ /(19|20|)\d\d/; # matches the null alternative '()\d\d',
  456. # because '20\d\d' can't match
  457. Alternations behave the same way in groups as out of them: at a given
  458. string position, the leftmost alternative that allows the regexp to
  459. match is taken. So in the last example at tth first string position,
  460. C<"20"> matches the second alternative, but there is nothing left over
  461. to match the next two digits C<\d\d>. So perl moves on to the next
  462. alternative, which is the null alternative and that works, since
  463. C<"20"> is two digits.
  464. The process of trying one alternative, seeing if it matches, and
  465. moving on to the next alternative if it doesn't, is called
  466. B<backtracking>. The term 'backtracking' comes from the idea that
  467. matching a regexp is like a walk in the woods. Successfully matching
  468. a regexp is like arriving at a destination. There are many possible
  469. trailheads, one for each string position, and each one is tried in
  470. order, left to right. From each trailhead there may be many paths,
  471. some of which get you there, and some which are dead ends. When you
  472. walk along a trail and hit a dead end, you have to backtrack along the
  473. trail to an earlier point to try another trail. If you hit your
  474. destination, you stop immediately and forget about trying all the
  475. other trails. You are persistent, and only if you have tried all the
  476. trails from all the trailheads and not arrived at your destination, do
  477. you declare failure. To be concrete, here is a step-by-step analysis
  478. of what perl does when it tries to match the regexp
  479. "abcde" =~ /(abd|abc)(df|d|de)/;
  480. =over 4
  481. =item 0
  482. Start with the first letter in the string 'a'.
  483. =item 1
  484. Try the first alternative in the first group 'abd'.
  485. =item 2
  486. Match 'a' followed by 'b'. So far so good.
  487. =item 3
  488. 'd' in the regexp doesn't match 'c' in the string - a dead
  489. end. So backtrack two characters and pick the second alternative in
  490. the first group 'abc'.
  491. =item 4
  492. Match 'a' followed by 'b' followed by 'c'. We are on a roll
  493. and have satisfied the first group. Set $1 to 'abc'.
  494. =item 5
  495. Move on to the second group and pick the first alternative
  496. 'df'.
  497. =item 6
  498. Match the 'd'.
  499. =item 7
  500. 'f' in the regexp doesn't match 'e' in the string, so a dead
  501. end. Backtrack one character and pick the second alternative in the
  502. second group 'd'.
  503. =item 8
  504. 'd' matches. The second grouping is satisfied, so set $2 to
  505. 'd'.
  506. =item 9
  507. We are at the end of the regexp, so we are done! We have
  508. matched 'abcd' out of the string "abcde".
  509. =back
  510. There are a couple of things to note about this analysis. First, the
  511. third alternative in the second group 'de' also allows a match, but we
  512. stopped before we got to it - at a given character position, leftmost
  513. wins. Second, we were able to get a match at the first character
  514. position of the string 'a'. If there were no matches at the first
  515. position, perl would move to the second character position 'b' and
  516. attempt the match all over again. Only when all possible paths at all
  517. possible character positions have been exhausted does perl give give
  518. up and declare S<C<$string =~ /(abd|abc)(df|d|de)/;> > to be false.
  519. Even with all this work, regexp matching happens remarkably fast. To
  520. speed things up, during compilation stage, perl compiles the regexp
  521. into a compact sequence of opcodes that can often fit inside a
  522. processor cache. When the code is executed, these opcodes can then run
  523. at full throttle and search very quickly.
  524. =head2 Extracting matches
  525. The grouping metacharacters C<()> also serve another completely
  526. different function: they allow the extraction of the parts of a string
  527. that matched. This is very useful to find out what matched and for
  528. text processing in general. For each grouping, the part that matched
  529. inside goes into the special variables C<$1>, C<$2>, etc. They can be
  530. used just as ordinary variables:
  531. # extract hours, minutes, seconds
  532. $time =~ /(\d\d):(\d\d):(\d\d)/; # match hh:mm:ss format
  533. $hours = $1;
  534. $minutes = $2;
  535. $seconds = $3;
  536. Now, we know that in scalar context,
  537. S<C<$time =~ /(\d\d):(\d\d):(\d\d)/> > returns a true or false
  538. value. In list context, however, it returns the list of matched values
  539. C<($1,$2,$3)>. So we could write the code more compactly as
  540. # extract hours, minutes, seconds
  541. ($hours, $minutes, $second) = ($time =~ /(\d\d):(\d\d):(\d\d)/);
  542. If the groupings in a regexp are nested, C<$1> gets the group with the
  543. leftmost opening parenthesis, C<$2> the next opening parenthesis,
  544. etc. For example, here is a complex regexp and the matching variables
  545. indicated below it:
  546. /(ab(cd|ef)((gi)|j))/;
  547. 1 2 34
  548. so that if the regexp matched, e.g., C<$2> would contain 'cd' or 'ef'.
  549. For convenience, perl sets C<$+> to the highest numbered C<$1>, C<$2>,
  550. ... that got assigned.
  551. Closely associated with the matching variables C<$1>, C<$2>, ... are
  552. the B<backreferences> C<\1>, C<\2>, ... . Backreferences are simply
  553. matching variables that can be used I<inside> a regexp. This is a
  554. really nice feature - what matches later in a regexp can depend on
  555. what matched earlier in the regexp. Suppose we wanted to look
  556. for doubled words in text, like 'the the'. The following regexp finds
  557. all 3-letter doubles with a space in between:
  558. /(\w\w\w)\s\1/;
  559. The grouping assigns a value to \1, so that the same 3 letter sequence
  560. is used for both parts. Here are some words with repeated parts:
  561. % simple_grep '^(\w\w\w\w|\w\w\w|\w\w|\w)\1$' /usr/dict/words
  562. beriberi
  563. booboo
  564. coco
  565. mama
  566. murmur
  567. papa
  568. The regexp has a single grouping which considers 4-letter
  569. combinations, then 3-letter combinations, etc. and uses C<\1> to look for
  570. a repeat. Although C<$1> and C<\1> represent the same thing, care should be
  571. taken to use matched variables C<$1>, C<$2>, ... only outside a regexp
  572. and backreferences C<\1>, C<\2>, ... only inside a regexp; not doing
  573. so may lead to surprising and/or undefined results.
  574. In addition to what was matched, Perl 5.6.0 also provides the
  575. positions of what was matched with the C<@-> and C<@+>
  576. arrays. C<$-[0]> is the position of the start of the entire match and
  577. C<$+[0]> is the position of the end. Similarly, C<$-[n]> is the
  578. position of the start of the C<$n> match and C<$+[n]> is the position
  579. of the end. If C<$n> is undefined, so are C<$-[n]> and C<$+[n]>. Then
  580. this code
  581. $x = "Mmm...donut, thought Homer";
  582. $x =~ /^(Mmm|Yech)\.\.\.(donut|peas)/; # matches
  583. foreach $expr (1..$#-) {
  584. print "Match $expr: '${$expr}' at position ($-[$expr],$+[$expr])\n";
  585. }
  586. prints
  587. Match 1: 'Mmm' at position (0,3)
  588. Match 2: 'donut' at position (6,11)
  589. Even if there are no groupings in a regexp, it is still possible to
  590. find out what exactly matched in a string. If you use them, perl
  591. will set C<$`> to the part of the string before the match, will set C<$&>
  592. to the part of the string that matched, and will set C<$'> to the part
  593. of the string after the match. An example:
  594. $x = "the cat caught the mouse";
  595. $x =~ /cat/; # $` = 'the ', $& = 'cat', $' = ' caught the mouse'
  596. $x =~ /the/; # $` = '', $& = 'the', $' = ' cat caught the mouse'
  597. In the second match, S<C<$` = ''> > because the regexp matched at the
  598. first character position in the string and stopped, it never saw the
  599. second 'the'. It is important to note that using C<$`> and C<$'>
  600. slows down regexp matching quite a bit, and C< $& > slows it down to a
  601. lesser extent, because if they are used in one regexp in a program,
  602. they are generated for <all> regexps in the program. So if raw
  603. performance is a goal of your application, they should be avoided.
  604. If you need them, use C<@-> and C<@+> instead:
  605. $` is the same as substr( $x, 0, $-[0] )
  606. $& is the same as substr( $x, $-[0], $+[0]-$-[0] )
  607. $' is the same as substr( $x, $+[0] )
  608. =head2 Matching repetitions
  609. The examples in the previous section display an annoying weakness. We
  610. were only matching 3-letter words, or syllables of 4 letters or
  611. less. We'd like to be able to match words or syllables of any length,
  612. without writing out tedious alternatives like
  613. C<\w\w\w\w|\w\w\w|\w\w|\w>.
  614. This is exactly the problem the B<quantifier> metacharacters C<?>,
  615. C<*>, C<+>, and C<{}> were created for. They allow us to determine the
  616. number of repeats of a portion of a regexp we consider to be a
  617. match. Quantifiers are put immediately after the character, character
  618. class, or grouping that we want to specify. They have the following
  619. meanings:
  620. =over 4
  621. =item *
  622. C<a?> = match 'a' 1 or 0 times
  623. =item *
  624. C<a*> = match 'a' 0 or more times, i.e., any number of times
  625. =item *
  626. C<a+> = match 'a' 1 or more times, i.e., at least once
  627. =item *
  628. C<a{n,m}> = match at least C<n> times, but not more than C<m>
  629. times.
  630. =item *
  631. C<a{n,}> = match at least C<n> or more times
  632. =item *
  633. C<a{n}> = match exactly C<n> times
  634. =back
  635. Here are some examples:
  636. /[a-z]+\s+\d*/; # match a lowercase word, at least some space, and
  637. # any number of digits
  638. /(\w+)\s+\1/; # match doubled words of arbitrary length
  639. /y(es)?/i; # matches 'y', 'Y', or a case-insensitive 'yes'
  640. $year =~ /\d{2,4}/; # make sure year is at least 2 but not more
  641. # than 4 digits
  642. $year =~ /\d{4}|\d{2}/; # better match; throw out 3 digit dates
  643. $year =~ /\d{2}(\d{2})?/; # same thing written differently. However,
  644. # this produces $1 and the other does not.
  645. % simple_grep '^(\w+)\1$' /usr/dict/words # isn't this easier?
  646. beriberi
  647. booboo
  648. coco
  649. mama
  650. murmur
  651. papa
  652. For all of these quantifiers, perl will try to match as much of the
  653. string as possible, while still allowing the regexp to succeed. Thus
  654. with C</a?.../>, perl will first try to match the regexp with the C<a>
  655. present; if that fails, perl will try to match the regexp without the
  656. C<a> present. For the quantifier C<*>, we get the following:
  657. $x = "the cat in the hat";
  658. $x =~ /^(.*)(cat)(.*)$/; # matches,
  659. # $1 = 'the '
  660. # $2 = 'cat'
  661. # $3 = ' in the hat'
  662. Which is what we might expect, the match finds the only C<cat> in the
  663. string and locks onto it. Consider, however, this regexp:
  664. $x =~ /^(.*)(at)(.*)$/; # matches,
  665. # $1 = 'the cat in the h'
  666. # $2 = 'at'
  667. # $3 = '' (0 matches)
  668. One might initially guess that perl would find the C<at> in C<cat> and
  669. stop there, but that wouldn't give the longest possible string to the
  670. first quantifier C<.*>. Instead, the first quantifier C<.*> grabs as
  671. much of the string as possible while still having the regexp match. In
  672. this example, that means having the C<at> sequence with the final C<at>
  673. in the string. The other important principle illustrated here is that
  674. when there are two or more elements in a regexp, the I<leftmost>
  675. quantifier, if there is one, gets to grab as much the string as
  676. possible, leaving the rest of the regexp to fight over scraps. Thus in
  677. our example, the first quantifier C<.*> grabs most of the string, while
  678. the second quantifier C<.*> gets the empty string. Quantifiers that
  679. grab as much of the string as possible are called B<maximal match> or
  680. B<greedy> quantifiers.
  681. When a regexp can match a string in several different ways, we can use
  682. the principles above to predict which way the regexp will match:
  683. =over 4
  684. =item *
  685. Principle 0: Taken as a whole, any regexp will be matched at the
  686. earliest possible position in the string.
  687. =item *
  688. Principle 1: In an alternation C<a|b|c...>, the leftmost alternative
  689. that allows a match for the whole regexp will be the one used.
  690. =item *
  691. Principle 2: The maximal matching quantifiers C<?>, C<*>, C<+> and
  692. C<{n,m}> will in general match as much of the string as possible while
  693. still allowing the whole regexp to match.
  694. =item *
  695. Principle 3: If there are two or more elements in a regexp, the
  696. leftmost greedy quantifier, if any, will match as much of the string
  697. as possible while still allowing the whole regexp to match. The next
  698. leftmost greedy quantifier, if any, will try to match as much of the
  699. string remaining available to it as possible, while still allowing the
  700. whole regexp to match. And so on, until all the regexp elements are
  701. satisfied.
  702. =back
  703. As we have seen above, Principle 0 overrides the others - the regexp
  704. will be matched as early as possible, with the other principles
  705. determining how the regexp matches at that earliest character
  706. position.
  707. Here is an example of these principles in action:
  708. $x = "The programming republic of Perl";
  709. $x =~ /^(.+)(e|r)(.*)$/; # matches,
  710. # $1 = 'The programming republic of Pe'
  711. # $2 = 'r'
  712. # $3 = 'l'
  713. This regexp matches at the earliest string position, C<'T'>. One
  714. might think that C<e>, being leftmost in the alternation, would be
  715. matched, but C<r> produces the longest string in the first quantifier.
  716. $x =~ /(m{1,2})(.*)$/; # matches,
  717. # $1 = 'mm'
  718. # $2 = 'ing republic of Perl'
  719. Here, The earliest possible match is at the first C<'m'> in
  720. C<programming>. C<m{1,2}> is the first quantifier, so it gets to match
  721. a maximal C<mm>.
  722. $x =~ /.*(m{1,2})(.*)$/; # matches,
  723. # $1 = 'm'
  724. # $2 = 'ing republic of Perl'
  725. Here, the regexp matches at the start of the string. The first
  726. quantifier C<.*> grabs as much as possible, leaving just a single
  727. C<'m'> for the second quantifier C<m{1,2}>.
  728. $x =~ /(.?)(m{1,2})(.*)$/; # matches,
  729. # $1 = 'a'
  730. # $2 = 'mm'
  731. # $3 = 'ing republic of Perl'
  732. Here, C<.?> eats its maximal one character at the earliest possible
  733. position in the string, C<'a'> in C<programming>, leaving C<m{1,2}>
  734. the opportunity to match both C<m>'s. Finally,
  735. "aXXXb" =~ /(X*)/; # matches with $1 = ''
  736. because it can match zero copies of C<'X'> at the beginning of the
  737. string. If you definitely want to match at least one C<'X'>, use
  738. C<X+>, not C<X*>.
  739. Sometimes greed is not good. At times, we would like quantifiers to
  740. match a I<minimal> piece of string, rather than a maximal piece. For
  741. this purpose, Larry Wall created the S<B<minimal match> > or
  742. B<non-greedy> quantifiers C<??>,C<*?>, C<+?>, and C<{}?>. These are
  743. the usual quantifiers with a C<?> appended to them. They have the
  744. following meanings:
  745. =over 4
  746. =item *
  747. C<a??> = match 'a' 0 or 1 times. Try 0 first, then 1.
  748. =item *
  749. C<a*?> = match 'a' 0 or more times, i.e., any number of times,
  750. but as few times as possible
  751. =item *
  752. C<a+?> = match 'a' 1 or more times, i.e., at least once, but
  753. as few times as possible
  754. =item *
  755. C<a{n,m}?> = match at least C<n> times, not more than C<m>
  756. times, as few times as possible
  757. =item *
  758. C<a{n,}?> = match at least C<n> times, but as few times as
  759. possible
  760. =item *
  761. C<a{n}?> = match exactly C<n> times. Because we match exactly
  762. C<n> times, C<a{n}?> is equivalent to C<a{n}> and is just there for
  763. notational consistency.
  764. =back
  765. Let's look at the example above, but with minimal quantifiers:
  766. $x = "The programming republic of Perl";
  767. $x =~ /^(.+?)(e|r)(.*)$/; # matches,
  768. # $1 = 'Th'
  769. # $2 = 'e'
  770. # $3 = ' programming republic of Perl'
  771. The minimal string that will allow both the start of the string C<^>
  772. and the alternation to match is C<Th>, with the alternation C<e|r>
  773. matching C<e>. The second quantifier C<.*> is free to gobble up the
  774. rest of the string.
  775. $x =~ /(m{1,2}?)(.*?)$/; # matches,
  776. # $1 = 'm'
  777. # $2 = 'ming republic of Perl'
  778. The first string position that this regexp can match is at the first
  779. C<'m'> in C<programming>. At this position, the minimal C<m{1,2}?>
  780. matches just one C<'m'>. Although the second quantifier C<.*?> would
  781. prefer to match no characters, it is constrained by the end-of-string
  782. anchor C<$> to match the rest of the string.
  783. $x =~ /(.*?)(m{1,2}?)(.*)$/; # matches,
  784. # $1 = 'The progra'
  785. # $2 = 'm'
  786. # $3 = 'ming republic of Perl'
  787. In this regexp, you might expect the first minimal quantifier C<.*?>
  788. to match the empty string, because it is not constrained by a C<^>
  789. anchor to match the beginning of the word. Principle 0 applies here,
  790. however. Because it is possible for the whole regexp to match at the
  791. start of the string, it I<will> match at the start of the string. Thus
  792. the first quantifier has to match everything up to the first C<m>. The
  793. second minimal quantifier matches just one C<m> and the third
  794. quantifier matches the rest of the string.
  795. $x =~ /(.??)(m{1,2})(.*)$/; # matches,
  796. # $1 = 'a'
  797. # $2 = 'mm'
  798. # $3 = 'ing republic of Perl'
  799. Just as in the previous regexp, the first quantifier C<.??> can match
  800. earliest at position C<'a'>, so it does. The second quantifier is
  801. greedy, so it matches C<mm>, and the third matches the rest of the
  802. string.
  803. We can modify principle 3 above to take into account non-greedy
  804. quantifiers:
  805. =over 4
  806. =item *
  807. Principle 3: If there are two or more elements in a regexp, the
  808. leftmost greedy (non-greedy) quantifier, if any, will match as much
  809. (little) of the string as possible while still allowing the whole
  810. regexp to match. The next leftmost greedy (non-greedy) quantifier, if
  811. any, will try to match as much (little) of the string remaining
  812. available to it as possible, while still allowing the whole regexp to
  813. match. And so on, until all the regexp elements are satisfied.
  814. =back
  815. Just like alternation, quantifiers are also susceptible to
  816. backtracking. Here is a step-by-step analysis of the example
  817. $x = "the cat in the hat";
  818. $x =~ /^(.*)(at)(.*)$/; # matches,
  819. # $1 = 'the cat in the h'
  820. # $2 = 'at'
  821. # $3 = '' (0 matches)
  822. =over 4
  823. =item 0
  824. Start with the first letter in the string 't'.
  825. =item 1
  826. The first quantifier '.*' starts out by matching the whole
  827. string 'the cat in the hat'.
  828. =item 2
  829. 'a' in the regexp element 'at' doesn't match the end of the
  830. string. Backtrack one character.
  831. =item 3
  832. 'a' in the regexp element 'at' still doesn't match the last
  833. letter of the string 't', so backtrack one more character.
  834. =item 4
  835. Now we can match the 'a' and the 't'.
  836. =item 5
  837. Move on to the third element '.*'. Since we are at the end of
  838. the string and '.*' can match 0 times, assign it the empty string.
  839. =item 6
  840. We are done!
  841. =back
  842. Most of the time, all this moving forward and backtracking happens
  843. quickly and searching is fast. There are some pathological regexps,
  844. however, whose execution time exponentially grows with the size of the
  845. string. A typical structure that blows up in your face is of the form
  846. /(a|b+)*/;
  847. The problem is the nested indeterminate quantifiers. There are many
  848. different ways of partitioning a string of length n between the C<+>
  849. and C<*>: one repetition with C<b+> of length n, two repetitions with
  850. the first C<b+> length k and the second with length n-k, m repetitions
  851. whose bits add up to length n, etc. In fact there are an exponential
  852. number of ways to partition a string as a function of length. A
  853. regexp may get lucky and match early in the process, but if there is
  854. no match, perl will try I<every> possibility before giving up. So be
  855. careful with nested C<*>'s, C<{n,m}>'s, and C<+>'s. The book
  856. I<Mastering regular expressions> by Jeffrey Friedl gives a wonderful
  857. discussion of this and other efficiency issues.
  858. =head2 Building a regexp
  859. At this point, we have all the basic regexp concepts covered, so let's
  860. give a more involved example of a regular expression. We will build a
  861. regexp that matches numbers.
  862. The first task in building a regexp is to decide what we want to match
  863. and what we want to exclude. In our case, we want to match both
  864. integers and floating point numbers and we want to reject any string
  865. that isn't a number.
  866. The next task is to break the problem down into smaller problems that
  867. are easily converted into a regexp.
  868. The simplest case is integers. These consist of a sequence of digits,
  869. with an optional sign in front. The digits we can represent with
  870. C<\d+> and the sign can be matched with C<[+-]>. Thus the integer
  871. regexp is
  872. /[+-]?\d+/; # matches integers
  873. A floating point number potentially has a sign, an integral part, a
  874. decimal point, a fractional part, and an exponent. One or more of these
  875. parts is optional, so we need to check out the different
  876. possibilities. Floating point numbers which are in proper form include
  877. 123., 0.345, .34, -1e6, and 25.4E-72. As with integers, the sign out
  878. front is completely optional and can be matched by C<[+-]?>. We can
  879. see that if there is no exponent, floating point numbers must have a
  880. decimal point, otherwise they are integers. We might be tempted to
  881. model these with C<\d*\.\d*>, but this would also match just a single
  882. decimal point, which is not a number. So the three cases of floating
  883. point number sans exponent are
  884. /[+-]?\d+\./; # 1., 321., etc.
  885. /[+-]?\.\d+/; # .1, .234, etc.
  886. /[+-]?\d+\.\d+/; # 1.0, 30.56, etc.
  887. These can be combined into a single regexp with a three-way alternation:
  888. /[+-]?(\d+\.\d+|\d+\.|\.\d+)/; # floating point, no exponent
  889. In this alternation, it is important to put C<'\d+\.\d+'> before
  890. C<'\d+\.'>. If C<'\d+\.'> were first, the regexp would happily match that
  891. and ignore the fractional part of the number.
  892. Now consider floating point numbers with exponents. The key
  893. observation here is that I<both> integers and numbers with decimal
  894. points are allowed in front of an exponent. Then exponents, like the
  895. overall sign, are independent of whether we are matching numbers with
  896. or without decimal points, and can be 'decoupled' from the
  897. mantissa. The overall form of the regexp now becomes clear:
  898. /^(optional sign)(integer | f.p. mantissa)(optional exponent)$/;
  899. The exponent is an C<e> or C<E>, followed by an integer. So the
  900. exponent regexp is
  901. /[eE][+-]?\d+/; # exponent
  902. Putting all the parts together, we get a regexp that matches numbers:
  903. /^[+-]?(\d+\.\d+|\d+\.|\.\d+|\d+)([eE][+-]?\d+)?$/; # Ta da!
  904. Long regexps like this may impress your friends, but can be hard to
  905. decipher. In complex situations like this, the C<//x> modifier for a
  906. match is invaluable. It allows one to put nearly arbitrary whitespace
  907. and comments into a regexp without affecting their meaning. Using it,
  908. we can rewrite our 'extended' regexp in the more pleasing form
  909. /^
  910. [+-]? # first, match an optional sign
  911. ( # then match integers or f.p. mantissas:
  912. \d+\.\d+ # mantissa of the form a.b
  913. |\d+\. # mantissa of the form a.
  914. |\.\d+ # mantissa of the form .b
  915. |\d+ # integer of the form a
  916. )
  917. ([eE][+-]?\d+)? # finally, optionally match an exponent
  918. $/x;
  919. If whitespace is mostly irrelevant, how does one include space
  920. characters in an extended regexp? The answer is to backslash it
  921. S<C<'\ '> > or put it in a character class S<C<[ ]> >. The same thing
  922. goes for pound signs, use C<\#> or C<[#]>. For instance, Perl allows
  923. a space between the sign and the mantissa/integer, and we could add
  924. this to our regexp as follows:
  925. /^
  926. [+-]?\ * # first, match an optional sign *and space*
  927. ( # then match integers or f.p. mantissas:
  928. \d+\.\d+ # mantissa of the form a.b
  929. |\d+\. # mantissa of the form a.
  930. |\.\d+ # mantissa of the form .b
  931. |\d+ # integer of the form a
  932. )
  933. ([eE][+-]?\d+)? # finally, optionally match an exponent
  934. $/x;
  935. In this form, it is easier to see a way to simplify the
  936. alternation. Alternatives 1, 2, and 4 all start with C<\d+>, so it
  937. could be factored out:
  938. /^
  939. [+-]?\ * # first, match an optional sign
  940. ( # then match integers or f.p. mantissas:
  941. \d+ # start out with a ...
  942. (
  943. \.\d* # mantissa of the form a.b or a.
  944. )? # ? takes care of integers of the form a
  945. |\.\d+ # mantissa of the form .b
  946. )
  947. ([eE][+-]?\d+)? # finally, optionally match an exponent
  948. $/x;
  949. or written in the compact form,
  950. /^[+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/;
  951. This is our final regexp. To recap, we built a regexp by
  952. =over 4
  953. =item *
  954. specifying the task in detail,
  955. =item *
  956. breaking down the problem into smaller parts,
  957. =item *
  958. translating the small parts into regexps,
  959. =item *
  960. combining the regexps,
  961. =item *
  962. and optimizing the final combined regexp.
  963. =back
  964. These are also the typical steps involved in writing a computer
  965. program. This makes perfect sense, because regular expressions are
  966. essentially programs written a little computer language that specifies
  967. patterns.
  968. =head2 Using regular expressions in Perl
  969. The last topic of Part 1 briefly covers how regexps are used in Perl
  970. programs. Where do they fit into Perl syntax?
  971. We have already introduced the matching operator in its default
  972. C</regexp/> and arbitrary delimiter C<m!regexp!> forms. We have used
  973. the binding operator C<=~> and its negation C<!~> to test for string
  974. matches. Associated with the matching operator, we have discussed the
  975. single line C<//s>, multi-line C<//m>, case-insensitive C<//i> and
  976. extended C<//x> modifiers.
  977. There are a few more things you might want to know about matching
  978. operators. First, we pointed out earlier that variables in regexps are
  979. substituted before the regexp is evaluated:
  980. $pattern = 'Seuss';
  981. while (<>) {
  982. print if /$pattern/;
  983. }
  984. This will print any lines containing the word C<Seuss>. It is not as
  985. efficient as it could be, however, because perl has to re-evaluate
  986. C<$pattern> each time through the loop. If C<$pattern> won't be
  987. changing over the lifetime of the script, we can add the C<//o>
  988. modifier, which directs perl to only perform variable substitutions
  989. once:
  990. #!/usr/bin/perl
  991. # Improved simple_grep
  992. $regexp = shift;
  993. while (<>) {
  994. print if /$regexp/o; # a good deal faster
  995. }
  996. If you change C<$pattern> after the first substitution happens, perl
  997. will ignore it. If you don't want any substitutions at all, use the
  998. special delimiter C<m''>:
  999. $pattern = 'Seuss';
  1000. while (<>) {
  1001. print if m'$pattern'; # matches '$pattern', not 'Seuss'
  1002. }
  1003. C<m''> acts like single quotes on a regexp; all other C<m> delimiters
  1004. act like double quotes. If the regexp evaluates to the empty string,
  1005. the regexp in the I<last successful match> is used instead. So we have
  1006. "dog" =~ /d/; # 'd' matches
  1007. "dogbert =~ //; # this matches the 'd' regexp used before
  1008. The final two modifiers C<//g> and C<//c> concern multiple matches.
  1009. The modifier C<//g> stands for global matching and allows the the
  1010. matching operator to match within a string as many times as possible.
  1011. In scalar context, successive invocations against a string will have
  1012. `C<//g> jump from match to match, keeping track of position in the
  1013. string as it goes along. You can get or set the position with the
  1014. C<pos()> function.
  1015. The use of C<//g> is shown in the following example. Suppose we have
  1016. a string that consists of words separated by spaces. If we know how
  1017. many words there are in advance, we could extract the words using
  1018. groupings:
  1019. $x = "cat dog house"; # 3 words
  1020. $x =~ /^\s*(\w+)\s+(\w+)\s+(\w+)\s*$/; # matches,
  1021. # $1 = 'cat'
  1022. # $2 = 'dog'
  1023. # $3 = 'house'
  1024. But what if we had an indeterminate number of words? This is the sort
  1025. of task C<//g> was made for. To extract all words, form the simple
  1026. regexp C<(\w+)> and loop over all matches with C</(\w+)/g>:
  1027. while ($x =~ /(\w+)/g) {
  1028. print "Word is $1, ends at position ", pos $x, "\n";
  1029. }
  1030. prints
  1031. Word is cat, ends at position 3
  1032. Word is dog, ends at position 7
  1033. Word is house, ends at position 13
  1034. A failed match or changing the target string resets the position. If
  1035. you don't want the position reset after failure to match, add the
  1036. C<//c>, as in C</regexp/gc>. The current position in the string is
  1037. associated with the string, not the regexp. This means that different
  1038. strings have different positions and their respective positions can be
  1039. set or read independently.
  1040. In list context, C<//g> returns a list of matched groupings, or if
  1041. there are no groupings, a list of matches to the whole regexp. So if
  1042. we wanted just the words, we could use
  1043. @words = ($x =~ /(\w+)/g); # matches,
  1044. # $word[0] = 'cat'
  1045. # $word[1] = 'dog'
  1046. # $word[2] = 'house'
  1047. Closely associated with the C<//g> modifier is the C<\G> anchor. The
  1048. C<\G> anchor matches at the point where the previous C<//g> match left
  1049. off. C<\G> allows us to easily do context-sensitive matching:
  1050. $metric = 1; # use metric units
  1051. ...
  1052. $x = <FILE>; # read in measurement
  1053. $x =~ /^([+-]?\d+)\s*/g; # get magnitude
  1054. $weight = $1;
  1055. if ($metric) { # error checking
  1056. print "Units error!" unless $x =~ /\Gkg\./g;
  1057. }
  1058. else {
  1059. print "Units error!" unless $x =~ /\Glbs\./g;
  1060. }
  1061. $x =~ /\G\s+(widget|sprocket)/g; # continue processing
  1062. The combination of C<//g> and C<\G> allows us to process the string a
  1063. bit at a time and use arbitrary Perl logic to decide what to do next.
  1064. C<\G> is also invaluable in processing fixed length records with
  1065. regexps. Suppose we have a snippet of coding region DNA, encoded as
  1066. base pair letters C<ATCGTTGAAT...> and we want to find all the stop
  1067. codons C<TGA>. In a coding region, codons are 3-letter sequences, so
  1068. we can think of the DNA snippet as a sequence of 3-letter records. The
  1069. naive regexp
  1070. # expanded, this is "ATC GTT GAA TGC AAA TGA CAT GAC"
  1071. $dna = "ATCGTTGAATGCAAATGACATGAC";
  1072. $dna =~ /TGA/;
  1073. doesn't work; it may match an C<TGA>, but there is no guarantee that
  1074. the match is aligned with codon boundaries, e.g., the substring
  1075. S<C<GTT GAA> > gives a match. A better solution is
  1076. while ($dna =~ /(\w\w\w)*?TGA/g) { # note the minimal *?
  1077. print "Got a TGA stop codon at position ", pos $dna, "\n";
  1078. }
  1079. which prints
  1080. Got a TGA stop codon at position 18
  1081. Got a TGA stop codon at position 23
  1082. Position 18 is good, but position 23 is bogus. What happened?
  1083. The answer is that our regexp works well until we get past the last
  1084. real match. Then the regexp will fail to match a synchronized C<TGA>
  1085. and start stepping ahead one character position at a time, not what we
  1086. want. The solution is to use C<\G> to anchor the match to the codon
  1087. alignment:
  1088. while ($dna =~ /\G(\w\w\w)*?TGA/g) {
  1089. print "Got a TGA stop codon at position ", pos $dna, "\n";
  1090. }
  1091. This prints
  1092. Got a TGA stop codon at position 18
  1093. which is the correct answer. This example illustrates that it is
  1094. important not only to match what is desired, but to reject what is not
  1095. desired.
  1096. B<search and replace>
  1097. Regular expressions also play a big role in B<search and replace>
  1098. operations in Perl. Search and replace is accomplished with the
  1099. C<s///> operator. The general form is
  1100. C<s/regexp/replacement/modifiers>, with everything we know about
  1101. regexps and modifiers applying in this case as well. The
  1102. C<replacement> is a Perl double quoted string that replaces in the
  1103. string whatever is matched with the C<regexp>. The operator C<=~> is
  1104. also used here to associate a string with C<s///>. If matching
  1105. against C<$_>, the S<C<$_ =~> > can be dropped. If there is a match,
  1106. C<s///> returns the number of substitutions made, otherwise it returns
  1107. false. Here are a few examples:
  1108. $x = "Time to feed the cat!";
  1109. $x =~ s/cat/hacker/; # $x contains "Time to feed the hacker!"
  1110. if ($x =~ s/^(Time.*hacker)!$/$1 now!/) {
  1111. $more_insistent = 1;
  1112. }
  1113. $y = "'quoted words'";
  1114. $y =~ s/^'(.*)'$/$1/; # strip single quotes,
  1115. # $y contains "quoted words"
  1116. In the last example, the whole string was matched, but only the part
  1117. inside the single quotes was grouped. With the C<s///> operator, the
  1118. matched variables C<$1>, C<$2>, etc. are immediately available for use
  1119. in the replacement expression, so we use C<$1> to replace the quoted
  1120. string with just what was quoted. With the global modifier, C<s///g>
  1121. will search and replace all occurrences of the regexp in the string:
  1122. $x = "I batted 4 for 4";
  1123. $x =~ s/4/four/; # doesn't do it all:
  1124. # $x contains "I batted four for 4"
  1125. $x = "I batted 4 for 4";
  1126. $x =~ s/4/four/g; # does it all:
  1127. # $x contains "I batted four for four"
  1128. If you prefer 'regex' over 'regexp' in this tutorial, you could use
  1129. the following program to replace it:
  1130. % cat > simple_replace
  1131. #!/usr/bin/perl
  1132. $regexp = shift;
  1133. $replacement = shift;
  1134. while (<>) {
  1135. s/$regexp/$replacement/go;
  1136. print;
  1137. }
  1138. ^D
  1139. % simple_replace regexp regex perlretut.pod
  1140. In C<simple_replace> we used the C<s///g> modifier to replace all
  1141. occurrences of the regexp on each line and the C<s///o> modifier to
  1142. compile the regexp only once. As with C<simple_grep>, both the
  1143. C<print> and the C<s/$regexp/$replacement/go> use C<$_> implicitly.
  1144. A modifier available specifically to search and replace is the
  1145. C<s///e> evaluation modifier. C<s///e> wraps an C<eval{...}> around
  1146. the replacement string and the evaluated result is substituted for the
  1147. matched substring. C<s///e> is useful if you need to do a bit of
  1148. computation in the process of replacing text. This example counts
  1149. character frequencies in a line:
  1150. $x = "Bill the cat";
  1151. $x =~ s/(.)/$chars{$1}++;$1/eg; # final $1 replaces char with itself
  1152. print "frequency of '$_' is $chars{$_}\n"
  1153. foreach (sort {$chars{$b} <=> $chars{$a}} keys %chars);
  1154. This prints
  1155. frequency of ' ' is 2
  1156. frequency of 't' is 2
  1157. frequency of 'l' is 2
  1158. frequency of 'B' is 1
  1159. frequency of 'c' is 1
  1160. frequency of 'e' is 1
  1161. frequency of 'h' is 1
  1162. frequency of 'i' is 1
  1163. frequency of 'a' is 1
  1164. As with the match C<m//> operator, C<s///> can use other delimiters,
  1165. such as C<s!!!> and C<s{}{}>, and even C<s{}//>. If single quotes are
  1166. used C<s'''>, then the regexp and replacement are treated as single
  1167. quoted strings and there are no substitutions. C<s///> in list context
  1168. returns the same thing as in scalar context, i.e., the number of
  1169. matches.
  1170. B<The split operator>
  1171. The B<C<split> > function can also optionally use a matching operator
  1172. C<m//> to split a string. C<split /regexp/, string, limit> splits
  1173. C<string> into a list of substrings and returns that list. The regexp
  1174. is used to match the character sequence that the C<string> is split
  1175. with respect to. The C<limit>, if present, constrains splitting into
  1176. no more than C<limit> number of strings. For example, to split a
  1177. string into words, use
  1178. $x = "Calvin and Hobbes";
  1179. @words = split /\s+/, $x; # $word[0] = 'Calvin'
  1180. # $word[1] = 'and'
  1181. # $word[2] = 'Hobbes'
  1182. If the empty regexp C<//> is used, the regexp always matches and
  1183. the string is split into individual characters. If the regexp has
  1184. groupings, then list produced contains the matched substrings from the
  1185. groupings as well. For instance,
  1186. $x = "/usr/bin/perl";
  1187. @dirs = split m!/!, $x; # $dirs[0] = ''
  1188. # $dirs[1] = 'usr'
  1189. # $dirs[2] = 'bin'
  1190. # $dirs[3] = 'perl'
  1191. @parts = split m!(/)!, $x; # $parts[0] = ''
  1192. # $parts[1] = '/'
  1193. # $parts[2] = 'usr'
  1194. # $parts[3] = '/'
  1195. # $parts[4] = 'bin'
  1196. # $parts[5] = '/'
  1197. # $parts[6] = 'perl'
  1198. Since the first character of $x matched the regexp, C<split> prepended
  1199. an empty initial element to the list.
  1200. If you have read this far, congratulations! You now have all the basic
  1201. tools needed to use regular expressions to solve a wide range of text
  1202. processing problems. If this is your first time through the tutorial,
  1203. why not stop here and play around with regexps a while... S<Part 2>
  1204. concerns the more esoteric aspects of regular expressions and those
  1205. concepts certainly aren't needed right at the start.
  1206. =head1 Part 2: Power tools
  1207. OK, you know the basics of regexps and you want to know more. If
  1208. matching regular expressions is analogous to a walk in the woods, then
  1209. the tools discussed in Part 1 are analogous to topo maps and a
  1210. compass, basic tools we use all the time. Most of the tools in part 2
  1211. are are analogous to flare guns and satellite phones. They aren't used
  1212. too often on a hike, but when we are stuck, they can be invaluable.
  1213. What follows are the more advanced, less used, or sometimes esoteric
  1214. capabilities of perl regexps. In Part 2, we will assume you are
  1215. comfortable with the basics and concentrate on the new features.
  1216. =head2 More on characters, strings, and character classes
  1217. There are a number of escape sequences and character classes that we
  1218. haven't covered yet.
  1219. There are several escape sequences that convert characters or strings
  1220. between upper and lower case. C<\l> and C<\u> convert the next
  1221. character to lower or upper case, respectively:
  1222. $x = "perl";
  1223. $string =~ /\u$x/; # matches 'Perl' in $string
  1224. $x = "M(rs?|s)\\."; # note the double backslash
  1225. $string =~ /\l$x/; # matches 'mr.', 'mrs.', and 'ms.',
  1226. C<\L> and C<\U> converts a whole substring, delimited by C<\L> or
  1227. C<\U> and C<\E>, to lower or upper case:
  1228. $x = "This word is in lower case:\L SHOUT\E";
  1229. $x =~ /shout/; # matches
  1230. $x = "I STILL KEYPUNCH CARDS FOR MY 360"
  1231. $x =~ /\Ukeypunch/; # matches punch card string
  1232. If there is no C<\E>, case is converted until the end of the
  1233. string. The regexps C<\L\u$word> or C<\u\L$word> convert the first
  1234. character of C<$word> to uppercase and the rest of the characters to
  1235. lowercase.
  1236. Control characters can be escaped with C<\c>, so that a control-Z
  1237. character would be matched with C<\cZ>. The escape sequence
  1238. C<\Q>...C<\E> quotes, or protects most non-alphabetic characters. For
  1239. instance,
  1240. $x = "\QThat !^*&%~& cat!";
  1241. $x =~ /\Q!^*&%~&\E/; # check for rough language
  1242. It does not protect C<$> or C<@>, so that variables can still be
  1243. substituted.
  1244. With the advent of 5.6.0, perl regexps can handle more than just the
  1245. standard ASCII character set. Perl now supports B<Unicode>, a standard
  1246. for encoding the character sets from many of the world's written
  1247. languages. Unicode does this by allowing characters to be more than
  1248. one byte wide. Perl uses the UTF-8 encoding, in which ASCII characters
  1249. are still encoded as one byte, but characters greater than C<chr(127)>
  1250. may be stored as two or more bytes.
  1251. What does this mean for regexps? Well, regexp users don't need to know
  1252. much about perl's internal representation of strings. But they do need
  1253. to know 1) how to represent Unicode characters in a regexp and 2) when
  1254. a matching operation will treat the string to be searched as a
  1255. sequence of bytes (the old way) or as a sequence of Unicode characters
  1256. (the new way). The answer to 1) is that Unicode characters greater
  1257. than C<chr(127)> may be represented using the C<\x{hex}> notation,
  1258. with C<hex> a hexadecimal integer:
  1259. use utf8; # We will be doing Unicode processing
  1260. /\x{263a}/; # match a Unicode smiley face :)
  1261. Unicode characters in the range of 128-255 use two hexadecimal digits
  1262. with braces: C<\x{ab}>. Note that this is different than C<\xab>,
  1263. which is just a hexadecimal byte with no Unicode
  1264. significance.
  1265. Figuring out the hexadecimal sequence of a Unicode character you want
  1266. or deciphering someone else's hexadecimal Unicode regexp is about as
  1267. much fun as programming in machine code. So another way to specify
  1268. Unicode characters is to use the S<B<named character> > escape
  1269. sequence C<\N{name}>. C<name> is a name for the Unicode character, as
  1270. specified in the Unicode standard. For instance, if we wanted to
  1271. represent or match the astrological sign for the planet Mercury, we
  1272. could use
  1273. use utf8; # We will be doing Unicode processing
  1274. use charnames ":full"; # use named chars with Unicode full names
  1275. $x = "abc\N{MERCURY}def";
  1276. $x =~ /\N{MERCURY}/; # matches
  1277. One can also use short names or restrict names to a certain alphabet:
  1278. use utf8; # We will be doing Unicode processing
  1279. use charnames ':full';
  1280. print "\N{GREEK SMALL LETTER SIGMA} is called sigma.\n";
  1281. use charnames ":short";
  1282. print "\N{greek:Sigma} is an upper-case sigma.\n";
  1283. use charnames qw(greek);
  1284. print "\N{sigma} is Greek sigma\n";
  1285. A list of full names is found in the file Names.txt in the
  1286. lib/perl5/5.6.0/unicode directory.
  1287. The answer to requirement 2), as of 5.6.0, is that if a regexp
  1288. contains Unicode characters, the string is searched as a sequence of
  1289. Unicode characters. Otherwise, the string is searched as a sequence of
  1290. bytes. If the string is being searched as a sequence of Unicode
  1291. characters, but matching a single byte is required, we can use the C<\C>
  1292. escape sequence. C<\C> is a character class akin to C<.> except that
  1293. it matches I<any> byte 0-255. So
  1294. use utf8; # We will be doing Unicode processing
  1295. use charnames ":full"; # use named chars with Unicode full names
  1296. $x = "a";
  1297. $x =~ /\C/; # matches 'a', eats one byte
  1298. $x = "";
  1299. $x =~ /\C/; # doesn't match, no bytes to match
  1300. $x = "\N{MERCURY}"; # two-byte Unicode character
  1301. $x =~ /\C/; # matches, but dangerous!
  1302. The last regexp matches, but is dangerous because the string
  1303. I<character> position is no longer synchronized to the string I<byte>
  1304. position. This generates the warning 'Malformed UTF-8
  1305. character'. C<\C> is best used for matching the binary data in strings
  1306. with binary data intermixed with Unicode characters.
  1307. Let us now discuss the rest of the character classes. Just as with
  1308. Unicode characters, there are named Unicode character classes
  1309. represented by the C<\p{name}> escape sequence. Closely associated is
  1310. the C<\P{name}> character class, which is the negation of the
  1311. C<\p{name}> class. For example, to match lower and uppercase
  1312. characters,
  1313. use utf8; # We will be doing Unicode processing
  1314. use charnames ":full"; # use named chars with Unicode full names
  1315. $x = "BOB";
  1316. $x =~ /^\p{IsUpper}/; # matches, uppercase char class
  1317. $x =~ /^\P{IsUpper}/; # doesn't match, char class sans uppercase
  1318. $x =~ /^\p{IsLower}/; # doesn't match, lowercase char class
  1319. $x =~ /^\P{IsLower}/; # matches, char class sans lowercase
  1320. Here is the association between some Perl named classes and the
  1321. traditional Unicode classes:
  1322. Perl class name Unicode class name or regular expression
  1323. IsAlpha /^[LM]/
  1324. IsAlnum /^[LMN]/
  1325. IsASCII $code <= 127
  1326. IsCntrl /^C/
  1327. IsBlank $code =~ /^(0020|0009)$/ || /^Z[^lp]/
  1328. IsDigit Nd
  1329. IsGraph /^([LMNPS]|Co)/
  1330. IsLower Ll
  1331. IsPrint /^([LMNPS]|Co|Zs)/
  1332. IsPunct /^P/
  1333. IsSpace /^Z/ || ($code =~ /^(0009|000A|000B|000C|000D)$/
  1334. IsSpacePerl /^Z/ || ($code =~ /^(0009|000A|000C|000D)$/
  1335. IsUpper /^L[ut]/
  1336. IsWord /^[LMN]/ || $code eq "005F"
  1337. IsXDigit $code =~ /^00(3[0-9]|[46][1-6])$/
  1338. You can also use the official Unicode class names with the C<\p> and
  1339. C<\P>, like C<\p{L}> for Unicode 'letters', or C<\p{Lu}> for uppercase
  1340. letters, or C<\P{Nd}> for non-digits. If a C<name> is just one
  1341. letter, the braces can be dropped. For instance, C<\pM> is the
  1342. character class of Unicode 'marks'.
  1343. C<\X> is an abbreviation for a character class sequence that includes
  1344. the Unicode 'combining character sequences'. A 'combining character
  1345. sequence' is a base character followed by any number of combining
  1346. characters. An example of a combining character is an accent. Using
  1347. the Unicode full names, e.g., S<C<A + COMBINING RING> > is a combining
  1348. character sequence with base character C<A> and combining character
  1349. S<C<COMBINING RING> >, which translates in Danish to A with the circle
  1350. atop it, as in the word Angstrom. C<\X> is equivalent to C<\PM\pM*}>,
  1351. i.e., a non-mark followed by one or more marks.
  1352. As if all those classes weren't enough, Perl also defines POSIX style
  1353. character classes. These have the form C<[:name:]>, with C<name> the
  1354. name of the POSIX class. The POSIX classes are C<alpha>, C<alnum>,
  1355. C<ascii>, C<cntrl>, C<digit>, C<graph>, C<lower>, C<print>, C<punct>,
  1356. C<space>, C<upper>, and C<xdigit>, and two extensions, C<word> (a Perl
  1357. extension to match C<\w>), and C<blank> (a GNU extension). If C<utf8>
  1358. is being used, then these classes are defined the same as their
  1359. corresponding perl Unicode classes: C<[:upper:]> is the same as
  1360. C<\p{IsUpper}>, etc. The POSIX character classes, however, don't
  1361. require using C<utf8>. The C<[:digit:]>, C<[:word:]>, and
  1362. C<[:space:]> correspond to the familiar C<\d>, C<\w>, and C<\s>
  1363. character classes. To negate a POSIX class, put a C<^> in front of
  1364. the name, so that, e.g., C<[:^digit:]> corresponds to C<\D> and under
  1365. C<utf8>, C<\P{IsDigit}>. The Unicode and POSIX character classes can
  1366. be used just like C<\d>, both inside and outside of character classes:
  1367. /\s+[abc[:digit:]xyz]\s*/; # match a,b,c,x,y,z, or a digit
  1368. /^=item\s[:digit:]/; # match '=item',
  1369. # followed by a space and a digit
  1370. use utf8;
  1371. use charnames ":full";
  1372. /\s+[abc\p{IsDigit}xyz]\s+/; # match a,b,c,x,y,z, or a digit
  1373. /^=item\s\p{IsDigit}/; # match '=item',
  1374. # followed by a space and a digit
  1375. Whew! That is all the rest of the characters and character classes.
  1376. =head2 Compiling and saving regular expressions
  1377. In Part 1 we discussed the C<//o> modifier, which compiles a regexp
  1378. just once. This suggests that a compiled regexp is some data structure
  1379. that can be stored once and used again and again. The regexp quote
  1380. C<qr//> does exactly that: C<qr/string/> compiles the C<string> as a
  1381. regexp and transforms the result into a form that can be assigned to a
  1382. variable:
  1383. $reg = qr/foo+bar?/; # reg contains a compiled regexp
  1384. Then C<$reg> can be used as a regexp:
  1385. $x = "fooooba";
  1386. $x =~ $reg; # matches, just like /foo+bar?/
  1387. $x =~ /$reg/; # same thing, alternate form
  1388. C<$reg> can also be interpolated into a larger regexp:
  1389. $x =~ /(abc)?$reg/; # still matches
  1390. As with the matching operator, the regexp quote can use different
  1391. delimiters, e.g., C<qr!!>, C<qr{}> and C<qr~~>. The single quote
  1392. delimiters C<qr''> prevent any interpolation from taking place.
  1393. Pre-compiled regexps are useful for creating dynamic matches that
  1394. don't need to be recompiled each time they are encountered. Using
  1395. pre-compiled regexps, C<simple_grep> program can be expanded into a
  1396. program that matches multiple patterns:
  1397. % cat > multi_grep
  1398. #!/usr/bin/perl
  1399. # multi_grep - match any of <number> regexps
  1400. # usage: multi_grep <number> regexp1 regexp2 ... file1 file2 ...
  1401. $number = shift;
  1402. $regexp[$_] = shift foreach (0..$number-1);
  1403. @compiled = map qr/$_/, @regexp;
  1404. while ($line = <>) {
  1405. foreach $pattern (@compiled) {
  1406. if ($line =~ /$pattern/) {
  1407. print $line;
  1408. last; # we matched, so move onto the next line
  1409. }
  1410. }
  1411. }
  1412. ^D
  1413. % multi_grep 2 last for multi_grep
  1414. $regexp[$_] = shift foreach (0..$number-1);
  1415. foreach $pattern (@compiled) {
  1416. last;
  1417. Storing pre-compiled regexps in an array C<@compiled> allows us to
  1418. simply loop through the regexps without any recompilation, thus gaining
  1419. flexibility without sacrificing speed.
  1420. =head2 Embedding comments and modifiers in a regular expression
  1421. Starting with this section, we will be discussing Perl's set of
  1422. B<extended patterns>. These are extensions to the traditional regular
  1423. expression syntax that provide powerful new tools for pattern
  1424. matching. We have already seen extensions in the form of the minimal
  1425. matching constructs C<??>, C<*?>, C<+?>, C<{n,m}?>, and C<{n,}?>. The
  1426. rest of the extensions below have the form C<(?char...)>, where the
  1427. C<char> is a character that determines the type of extension.
  1428. The first extension is an embedded comment C<(?#text)>. This embeds a
  1429. comment into the regular expression without affecting its meaning. The
  1430. comment should not have any closing parentheses in the text. An
  1431. example is
  1432. /(?# Match an integer:)[+-]?\d+/;
  1433. This style of commenting has been largely superseded by the raw,
  1434. freeform commenting that is allowed with the C<//x> modifier.
  1435. The modifiers C<//i>, C<//m>, C<//s>, and C<//x> can also embedded in
  1436. a regexp using C<(?i)>, C<(?m)>, C<(?s)>, and C<(?x)>. For instance,
  1437. /(?i)yes/; # match 'yes' case insensitively
  1438. /yes/i; # same thing
  1439. /(?x)( # freeform version of an integer regexp
  1440. [+-]? # match an optional sign
  1441. \d+ # match a sequence of digits
  1442. )
  1443. /x;
  1444. Embedded modifiers can have two important advantages over the usual
  1445. modifiers. Embedded modifiers allow a custom set of modifiers to
  1446. I<each> regexp pattern. This is great for matching an array of regexps
  1447. that must have different modifiers:
  1448. $pattern[0] = '(?i)doctor';
  1449. $pattern[1] = 'Johnson';
  1450. ...
  1451. while (<>) {
  1452. foreach $patt (@pattern) {
  1453. print if /$patt/;
  1454. }
  1455. }
  1456. The second advantage is that embedded modifiers only affect the regexp
  1457. inside the group the embedded modifier is contained in. So grouping
  1458. can be used to localize the modifier's effects:
  1459. /Answer: ((?i)yes)/; # matches 'Answer: yes', 'Answer: YES', etc.
  1460. Embedded modifiers can also turn off any modifiers already present
  1461. by using, e.g., C<(?-i)>. Modifiers can also be combined into
  1462. a single expression, e.g., C<(?s-i)> turns on single line mode and
  1463. turns off case insensitivity.
  1464. =head2 Non-capturing groupings
  1465. We noted in Part 1 that groupings C<()> had two distinct functions: 1)
  1466. group regexp elements together as a single unit, and 2) extract, or
  1467. capture, substrings that matched the regexp in the
  1468. grouping. Non-capturing groupings, denoted by C<(?:regexp)>, allow the
  1469. regexp to be treated as a single unit, but don't extract substrings or
  1470. set matching variables C<$1>, etc. Both capturing and non-capturing
  1471. groupings are allowed to co-exist in the same regexp. Because there is
  1472. no extraction, non-capturing groupings are faster than capturing
  1473. groupings. Non-capturing groupings are also handy for choosing exactly
  1474. which parts of a regexp are to be extracted to matching variables:
  1475. # match a number, $1-$4 are set, but we only want $1
  1476. /([+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)/;
  1477. # match a number faster , only $1 is set
  1478. /([+-]?\ *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)/;
  1479. # match a number, get $1 = whole number, $2 = exponent
  1480. /([+-]?\ *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE]([+-]?\d+))?)/;
  1481. Non-capturing groupings are also useful for removing nuisance
  1482. elements gathered from a split operation:
  1483. $x = '12a34b5';
  1484. @num = split /(a|b)/, $x; # @num = ('12','a','34','b','5')
  1485. @num = split /(?:a|b)/, $x; # @num = ('12','34','5')
  1486. Non-capturing groupings may also have embedded modifiers:
  1487. C<(?i-m:regexp)> is a non-capturing grouping that matches C<regexp>
  1488. case insensitively and turns off multi-line mode.
  1489. =head2 Looking ahead and looking behind
  1490. This section concerns the lookahead and lookbehind assertions. First,
  1491. a little background.
  1492. In Perl regular expressions, most regexp elements 'eat up' a certain
  1493. amount of string when they match. For instance, the regexp element
  1494. C<[abc}]> eats up one character of the string when it matches, in the
  1495. sense that perl moves to the next character position in the string
  1496. after the match. There are some elements, however, that don't eat up
  1497. characters (advance the character position) if they match. The examples
  1498. we have seen so far are the anchors. The anchor C<^> matches the
  1499. beginning of the line, but doesn't eat any characters. Similarly, the
  1500. word boundary anchor C<\b> matches, e.g., if the character to the left
  1501. is a word character and the character to the right is a non-word
  1502. character, but it doesn't eat up any characters itself. Anchors are
  1503. examples of 'zero-width assertions'. Zero-width, because they consume
  1504. no characters, and assertions, because they test some property of the
  1505. string. In the context of our walk in the woods analogy to regexp
  1506. matching, most regexp elements move us along a trail, but anchors have
  1507. us stop a moment and check our surroundings. If the local environment
  1508. checks out, we can proceed forward. But if the local environment
  1509. doesn't satisfy us, we must backtrack.
  1510. Checking the environment entails either looking ahead on the trail,
  1511. looking behind, or both. C<^> looks behind, to see that there are no
  1512. characters before. C<$> looks ahead, to see that there are no
  1513. characters after. C<\b> looks both ahead and behind, to see if the
  1514. characters on either side differ in their 'word'-ness.
  1515. The lookahead and lookbehind assertions are generalizations of the
  1516. anchor concept. Lookahead and lookbehind are zero-width assertions
  1517. that let us specify which characters we want to test for. The
  1518. lookahead assertion is denoted by C<(?=regexp)> and the lookbehind
  1519. assertion is denoted by C<< (?<=fixed-regexp) >>. Some examples are
  1520. $x = "I catch the housecat 'Tom-cat' with catnip";
  1521. $x =~ /cat(?=\s+)/; # matches 'cat' in 'housecat'
  1522. @catwords = ($x =~ /(?<=\s)cat\w+/g); # matches,
  1523. # $catwords[0] = 'catch'
  1524. # $catwords[1] = 'catnip'
  1525. $x =~ /\bcat\b/; # matches 'cat' in 'Tom-cat'
  1526. $x =~ /(?<=\s)cat(?=\s)/; # doesn't match; no isolated 'cat' in
  1527. # middle of $x
  1528. Note that the parentheses in C<(?=regexp)> and C<< (?<=regexp) >> are
  1529. non-capturing, since these are zero-width assertions. Thus in the
  1530. second regexp, the substrings captured are those of the whole regexp
  1531. itself. Lookahead C<(?=regexp)> can match arbitrary regexps, but
  1532. lookbehind C<< (?<=fixed-regexp) >> only works for regexps of fixed
  1533. width, i.e., a fixed number of characters long. Thus
  1534. C<< (?<=(ab|bc)) >> is fine, but C<< (?<=(ab)*) >> is not. The
  1535. negated versions of the lookahead and lookbehind assertions are
  1536. denoted by C<(?!regexp)> and C<< (?<!fixed-regexp) >> respectively.
  1537. They evaluate true if the regexps do I<not> match:
  1538. $x = "foobar";
  1539. $x =~ /foo(?!bar)/; # doesn't match, 'bar' follows 'foo'
  1540. $x =~ /foo(?!baz)/; # matches, 'baz' doesn't follow 'foo'
  1541. $x =~ /(?<!\s)foo/; # matches, there is no \s before 'foo'
  1542. =head2 Using independent subexpressions to prevent backtracking
  1543. The last few extended patterns in this tutorial are experimental as of
  1544. 5.6.0. Play with them, use them in some code, but don't rely on them
  1545. just yet for production code.
  1546. S<B<Independent subexpressions> > are regular expressions, in the
  1547. context of a larger regular expression, that function independently of
  1548. the larger regular expression. That is, they consume as much or as
  1549. little of the string as they wish without regard for the ability of
  1550. the larger regexp to match. Independent subexpressions are represented
  1551. by C<< (?>regexp) >>. We can illustrate their behavior by first
  1552. considering an ordinary regexp:
  1553. $x = "ab";
  1554. $x =~ /a*ab/; # matches
  1555. This obviously matches, but in the process of matching, the
  1556. subexpression C<a*> first grabbed the C<a>. Doing so, however,
  1557. wouldn't allow the whole regexp to match, so after backtracking, C<a*>
  1558. eventually gave back the C<a> and matched the empty string. Here, what
  1559. C<a*> matched was I<dependent> on what the rest of the regexp matched.
  1560. Contrast that with an independent subexpression:
  1561. $x =~ /(?>a*)ab/; # doesn't match!
  1562. The independent subexpression C<< (?>a*) >> doesn't care about the rest
  1563. of the regexp, so it sees an C<a> and grabs it. Then the rest of the
  1564. regexp C<ab> cannot match. Because C<< (?>a*) >> is independent, there
  1565. is no backtracking and and the independent subexpression does not give
  1566. up its C<a>. Thus the match of the regexp as a whole fails. A similar
  1567. behavior occurs with completely independent regexps:
  1568. $x = "ab";
  1569. $x =~ /a*/g; # matches, eats an 'a'
  1570. $x =~ /\Gab/g; # doesn't match, no 'a' available
  1571. Here C<//g> and C<\G> create a 'tag team' handoff of the string from
  1572. one regexp to the other. Regexps with an independent subexpression are
  1573. much like this, with a handoff of the string to the independent
  1574. subexpression, and a handoff of the string back to the enclosing
  1575. regexp.
  1576. The ability of an independent subexpression to prevent backtracking
  1577. can be quite useful. Suppose we want to match a non-empty string
  1578. enclosed in parentheses up to two levels deep. Then the following
  1579. regexp matches:
  1580. $x = "abc(de(fg)h"; # unbalanced parentheses
  1581. $x =~ /\( ( [^()]+ | \([^()]*\) )+ \)/x;
  1582. The regexp matches an open parenthesis, one or more copies of an
  1583. alternation, and a close parenthesis. The alternation is two-way, with
  1584. the first alternative C<[^()]+> matching a substring with no
  1585. parentheses and the second alternative C<\([^()]*\)> matching a
  1586. substring delimited by parentheses. The problem with this regexp is
  1587. that it is pathological: it has nested indeterminate quantifiers
  1588. of the form C<(a+|b)+>. We discussed in Part 1 how nested quantifiers
  1589. like this could take an exponentially long time to execute if there
  1590. was no match possible. To prevent the exponential blowup, we need to
  1591. prevent useless backtracking at some point. This can be done by
  1592. enclosing the inner quantifier as an independent subexpression:
  1593. $x =~ /\( ( (?>[^()]+) | \([^()]*\) )+ \)/x;
  1594. Here, C<< (?>[^()]+) >> breaks the degeneracy of string partitioning
  1595. by gobbling up as much of the string as possible and keeping it. Then
  1596. match failures fail much more quickly.
  1597. =head2 Conditional expressions
  1598. A S<B<conditional expression> > is a form of if-then-else statement
  1599. that allows one to choose which patterns are to be matched, based on
  1600. some condition. There are two types of conditional expression:
  1601. C<(?(condition)yes-regexp)> and
  1602. C<(?(condition)yes-regexp|no-regexp)>. C<(?(condition)yes-regexp)> is
  1603. like an S<C<'if () {}'> > statement in Perl. If the C<condition> is true,
  1604. the C<yes-regexp> will be matched. If the C<condition> is false, the
  1605. C<yes-regexp> will be skipped and perl will move onto the next regexp
  1606. element. The second form is like an S<C<'if () {} else {}'> > statement
  1607. in Perl. If the C<condition> is true, the C<yes-regexp> will be
  1608. matched, otherwise the C<no-regexp> will be matched.
  1609. The C<condition> can have two forms. The first form is simply an
  1610. integer in parentheses C<(integer)>. It is true if the corresponding
  1611. backreference C<\integer> matched earlier in the regexp. The second
  1612. form is a bare zero width assertion C<(?...)>, either a
  1613. lookahead, a lookbehind, or a code assertion (discussed in the next
  1614. section).
  1615. The integer form of the C<condition> allows us to choose, with more
  1616. flexibility, what to match based on what matched earlier in the
  1617. regexp. This searches for words of the form C<"$x$x"> or
  1618. C<"$x$y$y$x">:
  1619. % simple_grep '^(\w+)(\w+)?(?(2)\2\1|\1)$' /usr/dict/words
  1620. beriberi
  1621. coco
  1622. couscous
  1623. deed
  1624. ...
  1625. toot
  1626. toto
  1627. tutu
  1628. The lookbehind C<condition> allows, along with backreferences,
  1629. an earlier part of the match to influence a later part of the
  1630. match. For instance,
  1631. /[ATGC]+(?(?<=AA)G|C)$/;
  1632. matches a DNA sequence such that it either ends in C<AAG>, or some
  1633. other base pair combination and C<C>. Note that the form is
  1634. C<< (?(?<=AA)G|C) >> and not C<< (?((?<=AA))G|C) >>; for the
  1635. lookahead, lookbehind or code assertions, the parentheses around the
  1636. conditional are not needed.
  1637. =head2 A bit of magic: executing Perl code in a regular expression
  1638. Normally, regexps are a part of Perl expressions.
  1639. S<B<Code evaluation> > expressions turn that around by allowing
  1640. arbitrary Perl code to be a part of of a regexp. A code evaluation
  1641. expression is denoted C<(?{code})>, with C<code> a string of Perl
  1642. statements.
  1643. Code expressions are zero-width assertions, and the value they return
  1644. depends on their environment. There are two possibilities: either the
  1645. code expression is used as a conditional in a conditional expression
  1646. C<(?(condition)...)>, or it is not. If the code expression is a
  1647. conditional, the code is evaluated and the result (i.e., the result of
  1648. the last statement) is used to determine truth or falsehood. If the
  1649. code expression is not used as a conditional, the assertion always
  1650. evaluates true and the result is put into the special variable
  1651. C<$^R>. The variable C<$^R> can then be used in code expressions later
  1652. in the regexp. Here are some silly examples:
  1653. $x = "abcdef";
  1654. $x =~ /abc(?{print "Hi Mom!";})def/; # matches,
  1655. # prints 'Hi Mom!'
  1656. $x =~ /aaa(?{print "Hi Mom!";})def/; # doesn't match,
  1657. # no 'Hi Mom!'
  1658. Pay careful attention to the next example:
  1659. $x =~ /abc(?{print "Hi Mom!";})ddd/; # doesn't match,
  1660. # no 'Hi Mom!'
  1661. # but why not?
  1662. At first glance, you'd think that it shouldn't print, because obviously
  1663. the C<ddd> isn't going to match the target string. But look at this
  1664. example:
  1665. $x =~ /abc(?{print "Hi Mom!";})[d]dd/; # doesn't match,
  1666. # but _does_ print
  1667. Hmm. What happened here? If you've been following along, you know that
  1668. the above pattern should be effectively the same as the last one --
  1669. enclosing the d in a character class isn't going to change what it
  1670. matches. So why does the first not print while the second one does?
  1671. The answer lies in the optimizations the REx engine makes. In the first
  1672. case, all the engine sees are plain old characters (aside from the
  1673. C<?{}> construct). It's smart enough to realize that the string 'ddd'
  1674. doesn't occur in our target string before actually running the pattern
  1675. through. But in the second case, we've tricked it into thinking that our
  1676. pattern is more complicated than it is. It takes a look, sees our
  1677. character class, and decides that it will have to actually run the
  1678. pattern to determine whether or not it matches, and in the process of
  1679. running it hits the print statement before it discovers that we don't
  1680. have a match.
  1681. To take a closer look at how the engine does optimizations, see the
  1682. section L<"Pragmas and debugging"> below.
  1683. More fun with C<?{}>:
  1684. $x =~ /(?{print "Hi Mom!";})/; # matches,
  1685. # prints 'Hi Mom!'
  1686. $x =~ /(?{$c = 1;})(?{print "$c";})/; # matches,
  1687. # prints '1'
  1688. $x =~ /(?{$c = 1;})(?{print "$^R";})/; # matches,
  1689. # prints '1'
  1690. The bit of magic mentioned in the section title occurs when the regexp
  1691. backtracks in the process of searching for a match. If the regexp
  1692. backtracks over a code expression and if the variables used within are
  1693. localized using C<local>, the changes in the variables produced by the
  1694. code expression are undone! Thus, if we wanted to count how many times
  1695. a character got matched inside a group, we could use, e.g.,
  1696. $x = "aaaa";
  1697. $count = 0; # initialize 'a' count
  1698. $c = "bob"; # test if $c gets clobbered
  1699. $x =~ /(?{local $c = 0;}) # initialize count
  1700. ( a # match 'a'
  1701. (?{local $c = $c + 1;}) # increment count
  1702. )* # do this any number of times,
  1703. aa # but match 'aa' at the end
  1704. (?{$count = $c;}) # copy local $c var into $count
  1705. /x;
  1706. print "'a' count is $count, \$c variable is '$c'\n";
  1707. This prints
  1708. 'a' count is 2, $c variable is 'bob'
  1709. If we replace the S<C< (?{local $c = $c + 1;})> > with
  1710. S<C< (?{$c = $c + 1;})> >, the variable changes are I<not> undone
  1711. during backtracking, and we get
  1712. 'a' count is 4, $c variable is 'bob'
  1713. Note that only localized variable changes are undone. Other side
  1714. effects of code expression execution are permanent. Thus
  1715. $x = "aaaa";
  1716. $x =~ /(a(?{print "Yow\n";}))*aa/;
  1717. produces
  1718. Yow
  1719. Yow
  1720. Yow
  1721. Yow
  1722. The result C<$^R> is automatically localized, so that it will behave
  1723. properly in the presence of backtracking.
  1724. This example uses a code expression in a conditional to match the
  1725. article 'the' in either English or German:
  1726. $lang = 'DE'; # use German
  1727. ...
  1728. $text = "das";
  1729. print "matched\n"
  1730. if $text =~ /(?(?{
  1731. $lang eq 'EN'; # is the language English?
  1732. })
  1733. the | # if so, then match 'the'
  1734. (die|das|der) # else, match 'die|das|der'
  1735. )
  1736. /xi;
  1737. Note that the syntax here is C<(?(?{...})yes-regexp|no-regexp)>, not
  1738. C<(?((?{...}))yes-regexp|no-regexp)>. In other words, in the case of a
  1739. code expression, we don't need the extra parentheses around the
  1740. conditional.
  1741. If you try to use code expressions with interpolating variables, perl
  1742. may surprise you:
  1743. $bar = 5;
  1744. $pat = '(?{ 1 })';
  1745. /foo(?{ $bar })bar/; # compiles ok, $bar not interpolated
  1746. /foo(?{ 1 })$bar/; # compile error!
  1747. /foo${pat}bar/; # compile error!
  1748. $pat = qr/(?{ $foo = 1 })/; # precompile code regexp
  1749. /foo${pat}bar/; # compiles ok
  1750. If a regexp has (1) code expressions and interpolating variables,or
  1751. (2) a variable that interpolates a code expression, perl treats the
  1752. regexp as an error. If the code expression is precompiled into a
  1753. variable, however, interpolating is ok. The question is, why is this
  1754. an error?
  1755. The reason is that variable interpolation and code expressions
  1756. together pose a security risk. The combination is dangerous because
  1757. many programmers who write search engines often take user input and
  1758. plug it directly into a regexp:
  1759. $regexp = <>; # read user-supplied regexp
  1760. $chomp $regexp; # get rid of possible newline
  1761. $text =~ /$regexp/; # search $text for the $regexp
  1762. If the C<$regexp> variable contains a code expression, the user could
  1763. then execute arbitrary Perl code. For instance, some joker could
  1764. search for S<C<system('rm -rf *');> > to erase your files. In this
  1765. sense, the combination of interpolation and code expressions B<taints>
  1766. your regexp. So by default, using both interpolation and code
  1767. expressions in the same regexp is not allowed. If you're not
  1768. concerned about malicious users, it is possible to bypass this
  1769. security check by invoking S<C<use re 'eval'> >:
  1770. use re 'eval'; # throw caution out the door
  1771. $bar = 5;
  1772. $pat = '(?{ 1 })';
  1773. /foo(?{ 1 })$bar/; # compiles ok
  1774. /foo${pat}bar/; # compiles ok
  1775. Another form of code expression is the S<B<pattern code expression> >.
  1776. The pattern code expression is like a regular code expression, except
  1777. that the result of the code evaluation is treated as a regular
  1778. expression and matched immediately. A simple example is
  1779. $length = 5;
  1780. $char = 'a';
  1781. $x = 'aaaaabb';
  1782. $x =~ /(??{$char x $length})/x; # matches, there are 5 of 'a'
  1783. This final example contains both ordinary and pattern code
  1784. expressions. It detects if a binary string C<1101010010001...> has a
  1785. Fibonacci spacing 0,1,1,2,3,5,... of the C<1>'s:
  1786. $s0 = 0; $s1 = 1; # initial conditions
  1787. $x = "1101010010001000001";
  1788. print "It is a Fibonacci sequence\n"
  1789. if $x =~ /^1 # match an initial '1'
  1790. (
  1791. (??{'0' x $s0}) # match $s0 of '0'
  1792. 1 # and then a '1'
  1793. (?{
  1794. $largest = $s0; # largest seq so far
  1795. $s2 = $s1 + $s0; # compute next term
  1796. $s0 = $s1; # in Fibonacci sequence
  1797. $s1 = $s2;
  1798. })
  1799. )+ # repeat as needed
  1800. $ # that is all there is
  1801. /x;
  1802. print "Largest sequence matched was $largest\n";
  1803. This prints
  1804. It is a Fibonacci sequence
  1805. Largest sequence matched was 5
  1806. Ha! Try that with your garden variety regexp package...
  1807. Note that the variables C<$s0> and C<$s1> are not substituted when the
  1808. regexp is compiled, as happens for ordinary variables outside a code
  1809. expression. Rather, the code expressions are evaluated when perl
  1810. encounters them during the search for a match.
  1811. The regexp without the C<//x> modifier is
  1812. /^1((??{'0'x$s0})1(?{$largest=$s0;$s2=$s1+$s0$s0=$s1;$s1=$s2;}))+$/;
  1813. and is a great start on an Obfuscated Perl entry :-) When working with
  1814. code and conditional expressions, the extended form of regexps is
  1815. almost necessary in creating and debugging regexps.
  1816. =head2 Pragmas and debugging
  1817. Speaking of debugging, there are several pragmas available to control
  1818. and debug regexps in Perl. We have already encountered one pragma in
  1819. the previous section, S<C<use re 'eval';> >, that allows variable
  1820. interpolation and code expressions to coexist in a regexp. The other
  1821. pragmas are
  1822. use re 'taint';
  1823. $tainted = <>;
  1824. @parts = ($tainted =~ /(\w+)\s+(\w+)/; # @parts is now tainted
  1825. The C<taint> pragma causes any substrings from a match with a tainted
  1826. variable to be tainted as well. This is not normally the case, as
  1827. regexps are often used to extract the safe bits from a tainted
  1828. variable. Use C<taint> when you are not extracting safe bits, but are
  1829. performing some other processing. Both C<taint> and C<eval> pragmas
  1830. are lexically scoped, which means they are in effect only until
  1831. the end of the block enclosing the pragmas.
  1832. use re 'debug';
  1833. /^(.*)$/s; # output debugging info
  1834. use re 'debugcolor';
  1835. /^(.*)$/s; # output debugging info in living color
  1836. The global C<debug> and C<debugcolor> pragmas allow one to get
  1837. detailed debugging info about regexp compilation and
  1838. execution. C<debugcolor> is the same as debug, except the debugging
  1839. information is displayed in color on terminals that can display
  1840. termcap color sequences. Here is example output:
  1841. % perl -e 'use re "debug"; "abc" =~ /a*b+c/;'
  1842. Compiling REx `a*b+c'
  1843. size 9 first at 1
  1844. 1: STAR(4)
  1845. 2: EXACT <a>(0)
  1846. 4: PLUS(7)
  1847. 5: EXACT <b>(0)
  1848. 7: EXACT <c>(9)
  1849. 9: END(0)
  1850. floating `bc' at 0..2147483647 (checking floating) minlen 2
  1851. Guessing start of match, REx `a*b+c' against `abc'...
  1852. Found floating substr `bc' at offset 1...
  1853. Guessed: match at offset 0
  1854. Matching REx `a*b+c' against `abc'
  1855. Setting an EVAL scope, savestack=3
  1856. 0 <> <abc> | 1: STAR
  1857. EXACT <a> can match 1 times out of 32767...
  1858. Setting an EVAL scope, savestack=3
  1859. 1 <a> <bc> | 4: PLUS
  1860. EXACT <b> can match 1 times out of 32767...
  1861. Setting an EVAL scope, savestack=3
  1862. 2 <ab> <c> | 7: EXACT <c>
  1863. 3 <abc> <> | 9: END
  1864. Match successful!
  1865. Freeing REx: `a*b+c'
  1866. If you have gotten this far into the tutorial, you can probably guess
  1867. what the different parts of the debugging output tell you. The first
  1868. part
  1869. Compiling REx `a*b+c'
  1870. size 9 first at 1
  1871. 1: STAR(4)
  1872. 2: EXACT <a>(0)
  1873. 4: PLUS(7)
  1874. 5: EXACT <b>(0)
  1875. 7: EXACT <c>(9)
  1876. 9: END(0)
  1877. describes the compilation stage. C<STAR(4)> means that there is a
  1878. starred object, in this case C<'a'>, and if it matches, goto line 4,
  1879. i.e., C<PLUS(7)>. The middle lines describe some heuristics and
  1880. optimizations performed before a match:
  1881. floating `bc' at 0..2147483647 (checking floating) minlen 2
  1882. Guessing start of match, REx `a*b+c' against `abc'...
  1883. Found floating substr `bc' at offset 1...
  1884. Guessed: match at offset 0
  1885. Then the match is executed and the remaining lines describe the
  1886. process:
  1887. Matching REx `a*b+c' against `abc'
  1888. Setting an EVAL scope, savestack=3
  1889. 0 <> <abc> | 1: STAR
  1890. EXACT <a> can match 1 times out of 32767...
  1891. Setting an EVAL scope, savestack=3
  1892. 1 <a> <bc> | 4: PLUS
  1893. EXACT <b> can match 1 times out of 32767...
  1894. Setting an EVAL scope, savestack=3
  1895. 2 <ab> <c> | 7: EXACT <c>
  1896. 3 <abc> <> | 9: END
  1897. Match successful!
  1898. Freeing REx: `a*b+c'
  1899. Each step is of the form S<C<< n <x> <y> >> >, with C<< <x> >> the
  1900. part of the string matched and C<< <y> >> the part not yet
  1901. matched. The S<C<< | 1: STAR >> > says that perl is at line number 1
  1902. n the compilation list above. See
  1903. L<perldebguts/"Debugging regular expressions"> for much more detail.
  1904. An alternative method of debugging regexps is to embed C<print>
  1905. statements within the regexp. This provides a blow-by-blow account of
  1906. the backtracking in an alternation:
  1907. "that this" =~ m@(?{print "Start at position ", pos, "\n";})
  1908. t(?{print "t1\n";})
  1909. h(?{print "h1\n";})
  1910. i(?{print "i1\n";})
  1911. s(?{print "s1\n";})
  1912. |
  1913. t(?{print "t2\n";})
  1914. h(?{print "h2\n";})
  1915. a(?{print "a2\n";})
  1916. t(?{print "t2\n";})
  1917. (?{print "Done at position ", pos, "\n";})
  1918. @x;
  1919. prints
  1920. Start at position 0
  1921. t1
  1922. h1
  1923. t2
  1924. h2
  1925. a2
  1926. t2
  1927. Done at position 4
  1928. =head1 BUGS
  1929. Code expressions, conditional expressions, and independent expressions
  1930. are B<experimental>. Don't use them in production code. Yet.
  1931. =head1 SEE ALSO
  1932. This is just a tutorial. For the full story on perl regular
  1933. expressions, see the L<perlre> regular expressions reference page.
  1934. For more information on the matching C<m//> and substitution C<s///>
  1935. operators, see L<perlop/"Regexp Quote-Like Operators">. For
  1936. information on the C<split> operation, see L<perlfunc/split>.
  1937. For an excellent all-around resource on the care and feeding of
  1938. regular expressions, see the book I<Mastering Regular Expressions> by
  1939. Jeffrey Friedl (published by O'Reilly, ISBN 1556592-257-3).
  1940. =head1 AUTHOR AND COPYRIGHT
  1941. Copyright (c) 2000 Mark Kvale
  1942. All rights reserved.
  1943. This document may be distributed under the same terms as Perl itself.
  1944. =head2 Acknowledgments
  1945. The inspiration for the stop codon DNA example came from the ZIP
  1946. code example in chapter 7 of I<Mastering Regular Expressions>.
  1947. The author would like to thank Jeff Pinyan, Andrew Johnson, Peter
  1948. Haworth, Ronald J Kimball, and Joe Smith for all their helpful
  1949. comments.
  1950. =cut