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.

503 lines
18 KiB

  1. =head1 NAME
  2. perlrequick - Perl regular expressions quick start
  3. =head1 DESCRIPTION
  4. This page covers the very basics of understanding, creating and
  5. using regular expressions ('regexes') in Perl.
  6. =head1 The Guide
  7. =head2 Simple word matching
  8. The simplest regex is simply a word, or more generally, a string of
  9. characters. A regex consisting of a word matches any string that
  10. contains that word:
  11. "Hello World" =~ /World/; # matches
  12. In this statement, C<World> is a regex and the C<//> enclosing
  13. C</World/> tells perl to search a string for a match. The operator
  14. C<=~> associates the string with the regex match and produces a true
  15. value if the regex matched, or false if the regex did not match. In
  16. our case, C<World> matches the second word in C<"Hello World">, so the
  17. expression is true. This idea has several variations.
  18. Expressions like this are useful in conditionals:
  19. print "It matches\n" if "Hello World" =~ /World/;
  20. The sense of the match can be reversed by using C<!~> operator:
  21. print "It doesn't match\n" if "Hello World" !~ /World/;
  22. The literal string in the regex can be replaced by a variable:
  23. $greeting = "World";
  24. print "It matches\n" if "Hello World" =~ /$greeting/;
  25. If you're matching against C<$_>, the C<$_ =~> part can be omitted:
  26. $_ = "Hello World";
  27. print "It matches\n" if /World/;
  28. Finally, the C<//> default delimiters for a match can be changed to
  29. arbitrary delimiters by putting an C<'m'> out front:
  30. "Hello World" =~ m!World!; # matches, delimited by '!'
  31. "Hello World" =~ m{World}; # matches, note the matching '{}'
  32. "/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin',
  33. # '/' becomes an ordinary char
  34. Regexes must match a part of the string I<exactly> in order for the
  35. statement to be true:
  36. "Hello World" =~ /world/; # doesn't match, case sensitive
  37. "Hello World" =~ /o W/; # matches, ' ' is an ordinary char
  38. "Hello World" =~ /World /; # doesn't match, no ' ' at end
  39. perl will always match at the earliest possible point in the string:
  40. "Hello World" =~ /o/; # matches 'o' in 'Hello'
  41. "That hat is red" =~ /hat/; # matches 'hat' in 'That'
  42. Not all characters can be used 'as is' in a match. Some characters,
  43. called B<metacharacters>, are reserved for use in regex notation.
  44. The metacharacters are
  45. {}[]()^$.|*+?\
  46. A metacharacter can be matched by putting a backslash before it:
  47. "2+2=4" =~ /2+2/; # doesn't match, + is a metacharacter
  48. "2+2=4" =~ /2\+2/; # matches, \+ is treated like an ordinary +
  49. 'C:\WIN32' =~ /C:\\WIN/; # matches
  50. "/usr/bin/perl" =~ /\/usr\/local\/bin\/perl/; # matches
  51. In the last regex, the forward slash C<'/'> is also backslashed,
  52. because it is used to delimit the regex.
  53. Non-printable ASCII characters are represented by B<escape sequences>.
  54. Common examples are C<\t> for a tab, C<\n> for a newline, and C<\r>
  55. for a carriage return. Arbitrary bytes are represented by octal
  56. escape sequences, e.g., C<\033>, or hexadecimal escape sequences,
  57. e.g., C<\x1B>:
  58. "1000\t2000" =~ m(0\t2) # matches
  59. "cat" =~ /\143\x61\x74/ # matches, but a weird way to spell cat
  60. Regexes are treated mostly as double quoted strings, so variable
  61. substitution works:
  62. $foo = 'house';
  63. 'cathouse' =~ /cat$foo/; # matches
  64. 'housecat' =~ /${foo}cat/; # matches
  65. With all of the regexes above, if the regex matched anywhere in the
  66. string, it was considered a match. To specify I<where> it should
  67. match, we would use the B<anchor> metacharacters C<^> and C<$>. The
  68. anchor C<^> means match at the beginning of the string and the anchor
  69. C<$> means match at the end of the string, or before a newline at the
  70. end of the string. Some examples:
  71. "housekeeper" =~ /keeper/; # matches
  72. "housekeeper" =~ /^keeper/; # doesn't match
  73. "housekeeper" =~ /keeper$/; # matches
  74. "housekeeper\n" =~ /keeper$/; # matches
  75. "housekeeper" =~ /^housekeeper$/; # matches
  76. =head2 Using character classes
  77. A B<character class> allows a set of possible characters, rather than
  78. just a single character, to match at a particular point in a regex.
  79. Character classes are denoted by brackets C<[...]>, with the set of
  80. characters to be possibly matched inside. Here are some examples:
  81. /cat/; # matches 'cat'
  82. /[bcr]at/; # matches 'bat', 'cat', or 'rat'
  83. "abc" =~ /[cab]/; # matches 'a'
  84. In the last statement, even though C<'c'> is the first character in
  85. the class, the earliest point at which the regex can match is C<'a'>.
  86. /[yY][eE][sS]/; # match 'yes' in a case-insensitive way
  87. # 'yes', 'Yes', 'YES', etc.
  88. /yes/i; # also match 'yes' in a case-insensitive way
  89. The last example shows a match with an C<'i'> B<modifier>, which makes
  90. the match case-insensitive.
  91. Character classes also have ordinary and special characters, but the
  92. sets of ordinary and special characters inside a character class are
  93. different than those outside a character class. The special
  94. characters for a character class are C<-]\^$> and are matched using an
  95. escape:
  96. /[\]c]def/; # matches ']def' or 'cdef'
  97. $x = 'bcr';
  98. /[$x]at/; # matches 'bat, 'cat', or 'rat'
  99. /[\$x]at/; # matches '$at' or 'xat'
  100. /[\\$x]at/; # matches '\at', 'bat, 'cat', or 'rat'
  101. The special character C<'-'> acts as a range operator within character
  102. classes, so that the unwieldy C<[0123456789]> and C<[abc...xyz]>
  103. become the svelte C<[0-9]> and C<[a-z]>:
  104. /item[0-9]/; # matches 'item0' or ... or 'item9'
  105. /[0-9a-fA-F]/; # matches a hexadecimal digit
  106. If C<'-'> is the first or last character in a character class, it is
  107. treated as an ordinary character.
  108. The special character C<^> in the first position of a character class
  109. denotes a B<negated character class>, which matches any character but
  110. those in the brackets. Both C<[...]> and C<[^...]> must match a
  111. character, or the match fails. Then
  112. /[^a]at/; # doesn't match 'aat' or 'at', but matches
  113. # all other 'bat', 'cat, '0at', '%at', etc.
  114. /[^0-9]/; # matches a non-numeric character
  115. /[a^]at/; # matches 'aat' or '^at'; here '^' is ordinary
  116. Perl has several abbreviations for common character classes:
  117. =over 4
  118. =item *
  119. \d is a digit and represents [0-9]
  120. =item *
  121. \s is a whitespace character and represents [\ \t\r\n\f]
  122. =item *
  123. \w is a word character (alphanumeric or _) and represents [0-9a-zA-Z_]
  124. =item *
  125. \D is a negated \d; it represents any character but a digit [^0-9]
  126. =item *
  127. \S is a negated \s; it represents any non-whitespace character [^\s]
  128. =item *
  129. \W is a negated \w; it represents any non-word character [^\w]
  130. =item *
  131. The period '.' matches any character but "\n"
  132. =back
  133. The C<\d\s\w\D\S\W> abbreviations can be used both inside and outside
  134. of character classes. Here are some in use:
  135. /\d\d:\d\d:\d\d/; # matches a hh:mm:ss time format
  136. /[\d\s]/; # matches any digit or whitespace character
  137. /\w\W\w/; # matches a word char, followed by a
  138. # non-word char, followed by a word char
  139. /..rt/; # matches any two chars, followed by 'rt'
  140. /end\./; # matches 'end.'
  141. /end[.]/; # same thing, matches 'end.'
  142. The S<B<word anchor> > C<\b> matches a boundary between a word
  143. character and a non-word character C<\w\W> or C<\W\w>:
  144. $x = "Housecat catenates house and cat";
  145. $x =~ /\bcat/; # matches cat in 'catenates'
  146. $x =~ /cat\b/; # matches cat in 'housecat'
  147. $x =~ /\bcat\b/; # matches 'cat' at end of string
  148. In the last example, the end of the string is considered a word
  149. boundary.
  150. =head2 Matching this or that
  151. We can match match different character strings with the B<alternation>
  152. metacharacter C<'|'>. To match C<dog> or C<cat>, we form the regex
  153. C<dog|cat>. As before, perl will try to match the regex at the
  154. earliest possible point in the string. At each character position,
  155. perl will first try to match the the first alternative, C<dog>. If
  156. C<dog> doesn't match, perl will then try the next alternative, C<cat>.
  157. If C<cat> doesn't match either, then the match fails and perl moves to
  158. the next position in the string. Some examples:
  159. "cats and dogs" =~ /cat|dog|bird/; # matches "cat"
  160. "cats and dogs" =~ /dog|cat|bird/; # matches "cat"
  161. Even though C<dog> is the first alternative in the second regex,
  162. C<cat> is able to match earlier in the string.
  163. "cats" =~ /c|ca|cat|cats/; # matches "c"
  164. "cats" =~ /cats|cat|ca|c/; # matches "cats"
  165. At a given character position, the first alternative that allows the
  166. regex match to succeed wil be the one that matches. Here, all the
  167. alternatives match at the first string position, so th first matches.
  168. =head2 Grouping things and hierarchical matching
  169. The B<grouping> metacharacters C<()> allow a part of a regex to be
  170. treated as a single unit. Parts of a regex are grouped by enclosing
  171. them in parentheses. The regex C<house(cat|keeper)> means match
  172. C<house> followed by either C<cat> or C<keeper>. Some more examples
  173. are
  174. /(a|b)b/; # matches 'ab' or 'bb'
  175. /(^a|b)c/; # matches 'ac' at start of string or 'bc' anywhere
  176. /house(cat|)/; # matches either 'housecat' or 'house'
  177. /house(cat(s|)|)/; # matches either 'housecats' or 'housecat' or
  178. # 'house'. Note groups can be nested.
  179. "20" =~ /(19|20|)\d\d/; # matches the null alternative '()\d\d',
  180. # because '20\d\d' can't match
  181. =head2 Extracting matches
  182. The grouping metacharacters C<()> also allow the extraction of the
  183. parts of a string that matched. For each grouping, the part that
  184. matched inside goes into the special variables C<$1>, C<$2>, etc.
  185. They can be used just as ordinary variables:
  186. # extract hours, minutes, seconds
  187. $time =~ /(\d\d):(\d\d):(\d\d)/; # match hh:mm:ss format
  188. $hours = $1;
  189. $minutes = $2;
  190. $seconds = $3;
  191. In list context, a match C</regex/> with groupings will return the
  192. list of matched values C<($1,$2,...)>. So we could rewrite it as
  193. ($hours, $minutes, $second) = ($time =~ /(\d\d):(\d\d):(\d\d)/);
  194. If the groupings in a regex are nested, C<$1> gets the group with the
  195. leftmost opening parenthesis, C<$2> the next opening parenthesis,
  196. etc. For example, here is a complex regex and the matching variables
  197. indicated below it:
  198. /(ab(cd|ef)((gi)|j))/;
  199. 1 2 34
  200. Associated with the matching variables C<$1>, C<$2>, ... are
  201. the B<backreferences> C<\1>, C<\2>, ... Backreferences are
  202. matching variables that can be used I<inside> a regex:
  203. /(\w\w\w)\s\1/; # find sequences like 'the the' in string
  204. C<$1>, C<$2>, ... should only be used outside of a regex, and C<\1>,
  205. C<\2>, ... only inside a regex.
  206. =head2 Matching repetitions
  207. The B<quantifier> metacharacters C<?>, C<*>, C<+>, and C<{}> allow us
  208. to determine the number of repeats of a portion of a regex we
  209. consider to be a match. Quantifiers are put immediately after the
  210. character, character class, or grouping that we want to specify. They
  211. have the following meanings:
  212. =over 4
  213. =item *
  214. C<a?> = match 'a' 1 or 0 times
  215. =item *
  216. C<a*> = match 'a' 0 or more times, i.e., any number of times
  217. =item *
  218. C<a+> = match 'a' 1 or more times, i.e., at least once
  219. =item *
  220. C<a{n,m}> = match at least C<n> times, but not more than C<m>
  221. times.
  222. =item *
  223. C<a{n,}> = match at least C<n> or more times
  224. =item *
  225. C<a{n}> = match exactly C<n> times
  226. =back
  227. Here are some examples:
  228. /[a-z]+\s+\d*/; # match a lowercase word, at least some space, and
  229. # any number of digits
  230. /(\w+)\s+\1/; # match doubled words of arbitrary length
  231. $year =~ /\d{2,4}/; # make sure year is at least 2 but not more
  232. # than 4 digits
  233. $year =~ /\d{4}|\d{2}/; # better match; throw out 3 digit dates
  234. These quantifiers will try to match as much of the string as possible,
  235. while still allowing the regex to match. So we have
  236. $x = 'the cat in the hat';
  237. $x =~ /^(.*)(at)(.*)$/; # matches,
  238. # $1 = 'the cat in the h'
  239. # $2 = 'at'
  240. # $3 = '' (0 matches)
  241. The first quantifier C<.*> grabs as much of the string as possible
  242. while still having the regex match. The second quantifier C<.*> has
  243. no string left to it, so it matches 0 times.
  244. =head2 More matching
  245. There are a few more things you might want to know about matching
  246. operators. In the code
  247. $pattern = 'Seuss';
  248. while (<>) {
  249. print if /$pattern/;
  250. }
  251. perl has to re-evaluate C<$pattern> each time through the loop. If
  252. C<$pattern> won't be changing, use the C<//o> modifier, to only
  253. perform variable substitutions once. If you don't want any
  254. substitutions at all, use the special delimiter C<m''>:
  255. $pattern = 'Seuss';
  256. m'$pattern'; # matches '$pattern', not 'Seuss'
  257. The global modifier C<//g> allows the matching operator to match
  258. within a string as many times as possible. In scalar context,
  259. successive matches against a string will have C<//g> jump from match
  260. to match, keeping track of position in the string as it goes along.
  261. You can get or set the position with the C<pos()> function.
  262. For example,
  263. $x = "cat dog house"; # 3 words
  264. while ($x =~ /(\w+)/g) {
  265. print "Word is $1, ends at position ", pos $x, "\n";
  266. }
  267. prints
  268. Word is cat, ends at position 3
  269. Word is dog, ends at position 7
  270. Word is house, ends at position 13
  271. A failed match or changing the target string resets the position. If
  272. you don't want the position reset after failure to match, add the
  273. C<//c>, as in C</regex/gc>.
  274. In list context, C<//g> returns a list of matched groupings, or if
  275. there are no groupings, a list of matches to the whole regex. So
  276. @words = ($x =~ /(\w+)/g); # matches,
  277. # $word[0] = 'cat'
  278. # $word[1] = 'dog'
  279. # $word[2] = 'house'
  280. =head2 Search and replace
  281. Search and replace is performed using C<s/regex/replacement/modifiers>.
  282. The C<replacement> is a Perl double quoted string that replaces in the
  283. string whatever is matched with the C<regex>. The operator C<=~> is
  284. also used here to associate a string with C<s///>. If matching
  285. against C<$_>, the S<C<$_ =~> > can be dropped. If there is a match,
  286. C<s///> returns the number of substitutions made, otherwise it returns
  287. false. Here are a few examples:
  288. $x = "Time to feed the cat!";
  289. $x =~ s/cat/hacker/; # $x contains "Time to feed the hacker!"
  290. $y = "'quoted words'";
  291. $y =~ s/^'(.*)'$/$1/; # strip single quotes,
  292. # $y contains "quoted words"
  293. With the C<s///> operator, the matched variables C<$1>, C<$2>, etc.
  294. are immediately available for use in the replacement expression. With
  295. the global modifier, C<s///g> will search and replace all occurrences
  296. of the regex in the string:
  297. $x = "I batted 4 for 4";
  298. $x =~ s/4/four/; # $x contains "I batted four for 4"
  299. $x = "I batted 4 for 4";
  300. $x =~ s/4/four/g; # $x contains "I batted four for four"
  301. The evaluation modifier C<s///e> wraps an C<eval{...}> around the
  302. replacement string and the evaluated result is substituted for the
  303. matched substring. Some examples:
  304. # reverse all the words in a string
  305. $x = "the cat in the hat";
  306. $x =~ s/(\w+)/reverse $1/ge; # $x contains "eht tac ni eht tah"
  307. # convert percentage to decimal
  308. $x = "A 39% hit rate";
  309. $x =~ s!(\d+)%!$1/100!e; # $x contains "A 0.39 hit rate"
  310. The last example shows that C<s///> can use other delimiters, such as
  311. C<s!!!> and C<s{}{}>, and even C<s{}//>. If single quotes are used
  312. C<s'''>, then the regex and replacement are treated as single quoted
  313. strings.
  314. =head2 The split operator
  315. C<split /regex/, string> splits C<string> into a list of substrings
  316. and returns that list. The regex determines the character sequence
  317. that C<string> is split with respect to. For example, to split a
  318. string into words, use
  319. $x = "Calvin and Hobbes";
  320. @word = split /\s+/, $x; # $word[0] = 'Calvin'
  321. # $word[1] = 'and'
  322. # $word[2] = 'Hobbes'
  323. To extract a comma-delimited list of numbers, use
  324. $x = "1.618,2.718, 3.142";
  325. @const = split /,\s*/, $x; # $const[0] = '1.618'
  326. # $const[1] = '2.718'
  327. # $const[2] = '3.142'
  328. If the empty regex C<//> is used, the string is split into individual
  329. characters. If the regex has groupings, then list produced contains
  330. the matched substrings from the groupings as well:
  331. $x = "/usr/bin";
  332. @parts = split m!(/)!, $x; # $parts[0] = ''
  333. # $parts[1] = '/'
  334. # $parts[2] = 'usr'
  335. # $parts[3] = '/'
  336. # $parts[4] = 'bin'
  337. Since the first character of $x matched the regex, C<split> prepended
  338. an empty initial element to the list.
  339. =head1 BUGS
  340. None.
  341. =head1 SEE ALSO
  342. This is just a quick start guide. For a more in-depth tutorial on
  343. regexes, see L<perlretut> and for the reference page, see L<perlre>.
  344. =head1 AUTHOR AND COPYRIGHT
  345. Copyright (c) 2000 Mark Kvale
  346. All rights reserved.
  347. This document may be distributed under the same terms as Perl itself.
  348. =head2 Acknowledgments
  349. The author would like to thank Mark-Jason Dominus, Tom Christiansen,
  350. Ilya Zakharevich, Brad Hughes, and Mike Giroux for all their helpful
  351. comments.
  352. =cut