Source code of Windows XP (NT5)
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.

633 lines
22 KiB

  1. =head1 NAME
  2. perlfaq6 - Regexps ($Revision: 1.25 $, $Date: 1999/01/08 04:50:47 $)
  3. =head1 DESCRIPTION
  4. This section is surprisingly small because the rest of the FAQ is
  5. littered with answers involving regular expressions. For example,
  6. decoding a URL and checking whether something is a number are handled
  7. with regular expressions, but those answers are found elsewhere in
  8. this document (in the section on Data and the Networking one on
  9. networking, to be precise).
  10. =head2 How can I hope to use regular expressions without creating illegible and unmaintainable code?
  11. Three techniques can make regular expressions maintainable and
  12. understandable.
  13. =over 4
  14. =item Comments Outside the Regexp
  15. Describe what you're doing and how you're doing it, using normal Perl
  16. comments.
  17. # turn the line into the first word, a colon, and the
  18. # number of characters on the rest of the line
  19. s/^(\w+)(.*)/ lc($1) . ":" . length($2) /meg;
  20. =item Comments Inside the Regexp
  21. The C</x> modifier causes whitespace to be ignored in a regexp pattern
  22. (except in a character class), and also allows you to use normal
  23. comments there, too. As you can imagine, whitespace and comments help
  24. a lot.
  25. C</x> lets you turn this:
  26. s{<(?:[^>'"]*|".*?"|'.*?')+>}{}gs;
  27. into this:
  28. s{ < # opening angle bracket
  29. (?: # Non-backreffing grouping paren
  30. [^>'"] * # 0 or more things that are neither > nor ' nor "
  31. | # or else
  32. ".*?" # a section between double quotes (stingy match)
  33. | # or else
  34. '.*?' # a section between single quotes (stingy match)
  35. ) + # all occurring one or more times
  36. > # closing angle bracket
  37. }{}gsx; # replace with nothing, i.e. delete
  38. It's still not quite so clear as prose, but it is very useful for
  39. describing the meaning of each part of the pattern.
  40. =item Different Delimiters
  41. While we normally think of patterns as being delimited with C</>
  42. characters, they can be delimited by almost any character. L<perlre>
  43. describes this. For example, the C<s///> above uses braces as
  44. delimiters. Selecting another delimiter can avoid quoting the
  45. delimiter within the pattern:
  46. s/\/usr\/local/\/usr\/share/g; # bad delimiter choice
  47. s#/usr/local#/usr/share#g; # better
  48. =back
  49. =head2 I'm having trouble matching over more than one line. What's wrong?
  50. Either you don't have more than one line in the string you're looking at
  51. (probably), or else you aren't using the correct modifier(s) on your
  52. pattern (possibly).
  53. There are many ways to get multiline data into a string. If you want
  54. it to happen automatically while reading input, you'll want to set $/
  55. (probably to '' for paragraphs or C<undef> for the whole file) to
  56. allow you to read more than one line at a time.
  57. Read L<perlre> to help you decide which of C</s> and C</m> (or both)
  58. you might want to use: C</s> allows dot to include newline, and C</m>
  59. allows caret and dollar to match next to a newline, not just at the
  60. end of the string. You do need to make sure that you've actually
  61. got a multiline string in there.
  62. For example, this program detects duplicate words, even when they span
  63. line breaks (but not paragraph ones). For this example, we don't need
  64. C</s> because we aren't using dot in a regular expression that we want
  65. to cross line boundaries. Neither do we need C</m> because we aren't
  66. wanting caret or dollar to match at any point inside the record next
  67. to newlines. But it's imperative that $/ be set to something other
  68. than the default, or else we won't actually ever have a multiline
  69. record read in.
  70. $/ = ''; # read in more whole paragraph, not just one line
  71. while ( <> ) {
  72. while ( /\b([\w'-]+)(\s+\1)+\b/gi ) { # word starts alpha
  73. print "Duplicate $1 at paragraph $.\n";
  74. }
  75. }
  76. Here's code that finds sentences that begin with "From " (which would
  77. be mangled by many mailers):
  78. $/ = ''; # read in more whole paragraph, not just one line
  79. while ( <> ) {
  80. while ( /^From /gm ) { # /m makes ^ match next to \n
  81. print "leading from in paragraph $.\n";
  82. }
  83. }
  84. Here's code that finds everything between START and END in a paragraph:
  85. undef $/; # read in whole file, not just one line or paragraph
  86. while ( <> ) {
  87. while ( /START(.*?)END/sm ) { # /s makes . cross line boundaries
  88. print "$1\n";
  89. }
  90. }
  91. =head2 How can I pull out lines between two patterns that are themselves on different lines?
  92. You can use Perl's somewhat exotic C<..> operator (documented in
  93. L<perlop>):
  94. perl -ne 'print if /START/ .. /END/' file1 file2 ...
  95. If you wanted text and not lines, you would use
  96. perl -0777 -ne 'print "$1\n" while /START(.*?)END/gs' file1 file2 ...
  97. But if you want nested occurrences of C<START> through C<END>, you'll
  98. run up against the problem described in the question in this section
  99. on matching balanced text.
  100. Here's another example of using C<..>:
  101. while (<>) {
  102. $in_header = 1 .. /^$/;
  103. $in_body = /^$/ .. eof();
  104. # now choose between them
  105. } continue {
  106. reset if eof(); # fix $.
  107. }
  108. =head2 I put a regular expression into $/ but it didn't work. What's wrong?
  109. $/ must be a string, not a regular expression. Awk has to be better
  110. for something. :-)
  111. Actually, you could do this if you don't mind reading the whole file
  112. into memory:
  113. undef $/;
  114. @records = split /your_pattern/, <FH>;
  115. The Net::Telnet module (available from CPAN) has the capability to
  116. wait for a pattern in the input stream, or timeout if it doesn't
  117. appear within a certain time.
  118. ## Create a file with three lines.
  119. open FH, ">file";
  120. print FH "The first line\nThe second line\nThe third line\n";
  121. close FH;
  122. ## Get a read/write filehandle to it.
  123. $fh = new FileHandle "+<file";
  124. ## Attach it to a "stream" object.
  125. use Net::Telnet;
  126. $file = new Net::Telnet (-fhopen => $fh);
  127. ## Search for the second line and print out the third.
  128. $file->waitfor('/second line\n/');
  129. print $file->getline;
  130. =head2 How do I substitute case insensitively on the LHS, but preserving case on the RHS?
  131. It depends on what you mean by "preserving case". The following
  132. script makes the substitution have the same case, letter by letter, as
  133. the original. If the substitution has more characters than the string
  134. being substituted, the case of the last character is used for the rest
  135. of the substitution.
  136. # Original by Nathan Torkington, massaged by Jeffrey Friedl
  137. #
  138. sub preserve_case($$)
  139. {
  140. my ($old, $new) = @_;
  141. my ($state) = 0; # 0 = no change; 1 = lc; 2 = uc
  142. my ($i, $oldlen, $newlen, $c) = (0, length($old), length($new));
  143. my ($len) = $oldlen < $newlen ? $oldlen : $newlen;
  144. for ($i = 0; $i < $len; $i++) {
  145. if ($c = substr($old, $i, 1), $c =~ /[\W\d_]/) {
  146. $state = 0;
  147. } elsif (lc $c eq $c) {
  148. substr($new, $i, 1) = lc(substr($new, $i, 1));
  149. $state = 1;
  150. } else {
  151. substr($new, $i, 1) = uc(substr($new, $i, 1));
  152. $state = 2;
  153. }
  154. }
  155. # finish up with any remaining new (for when new is longer than old)
  156. if ($newlen > $oldlen) {
  157. if ($state == 1) {
  158. substr($new, $oldlen) = lc(substr($new, $oldlen));
  159. } elsif ($state == 2) {
  160. substr($new, $oldlen) = uc(substr($new, $oldlen));
  161. }
  162. }
  163. return $new;
  164. }
  165. $a = "this is a TEsT case";
  166. $a =~ s/(test)/preserve_case($1, "success")/gie;
  167. print "$a\n";
  168. This prints:
  169. this is a SUcCESS case
  170. =head2 How can I make C<\w> match national character sets?
  171. See L<perllocale>.
  172. =head2 How can I match a locale-smart version of C</[a-zA-Z]/>?
  173. One alphabetic character would be C</[^\W\d_]/>, no matter what locale
  174. you're in. Non-alphabetics would be C</[\W\d_]/> (assuming you don't
  175. consider an underscore a letter).
  176. =head2 How can I quote a variable to use in a regexp?
  177. The Perl parser will expand $variable and @variable references in
  178. regular expressions unless the delimiter is a single quote. Remember,
  179. too, that the right-hand side of a C<s///> substitution is considered
  180. a double-quoted string (see L<perlop> for more details). Remember
  181. also that any regexp special characters will be acted on unless you
  182. precede the substitution with \Q. Here's an example:
  183. $string = "to die?";
  184. $lhs = "die?";
  185. $rhs = "sleep no more";
  186. $string =~ s/\Q$lhs/$rhs/;
  187. # $string is now "to sleep no more"
  188. Without the \Q, the regexp would also spuriously match "di".
  189. =head2 What is C</o> really for?
  190. Using a variable in a regular expression match forces a re-evaluation
  191. (and perhaps recompilation) each time through. The C</o> modifier
  192. locks in the regexp the first time it's used. This always happens in a
  193. constant regular expression, and in fact, the pattern was compiled
  194. into the internal format at the same time your entire program was.
  195. Use of C</o> is irrelevant unless variable interpolation is used in
  196. the pattern, and if so, the regexp engine will neither know nor care
  197. whether the variables change after the pattern is evaluated the I<very
  198. first> time.
  199. C</o> is often used to gain an extra measure of efficiency by not
  200. performing subsequent evaluations when you know it won't matter
  201. (because you know the variables won't change), or more rarely, when
  202. you don't want the regexp to notice if they do.
  203. For example, here's a "paragrep" program:
  204. $/ = ''; # paragraph mode
  205. $pat = shift;
  206. while (<>) {
  207. print if /$pat/o;
  208. }
  209. =head2 How do I use a regular expression to strip C style comments from a file?
  210. While this actually can be done, it's much harder than you'd think.
  211. For example, this one-liner
  212. perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c
  213. will work in many but not all cases. You see, it's too simple-minded for
  214. certain kinds of C programs, in particular, those with what appear to be
  215. comments in quoted strings. For that, you'd need something like this,
  216. created by Jeffrey Friedl:
  217. $/ = undef;
  218. $_ = <>;
  219. s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|\n+|.[^/"'\\]*)#$2#g;
  220. print;
  221. This could, of course, be more legibly written with the C</x> modifier, adding
  222. whitespace and comments.
  223. =head2 Can I use Perl regular expressions to match balanced text?
  224. Although Perl regular expressions are more powerful than "mathematical"
  225. regular expressions, because they feature conveniences like backreferences
  226. (C<\1> and its ilk), they still aren't powerful enough. You still need
  227. to use non-regexp techniques to parse balanced text, such as the text
  228. enclosed between matching parentheses or braces, for example.
  229. An elaborate subroutine (for 7-bit ASCII only) to pull out balanced
  230. and possibly nested single chars, like C<`> and C<'>, C<{> and C<}>,
  231. or C<(> and C<)> can be found in
  232. http://www.perl.com/CPAN/authors/id/TOMC/scripts/pull_quotes.gz .
  233. The C::Scan module from CPAN contains such subs for internal usage,
  234. but they are undocumented.
  235. =head2 What does it mean that regexps are greedy? How can I get around it?
  236. Most people mean that greedy regexps match as much as they can.
  237. Technically speaking, it's actually the quantifiers (C<?>, C<*>, C<+>,
  238. C<{}>) that are greedy rather than the whole pattern; Perl prefers local
  239. greed and immediate gratification to overall greed. To get non-greedy
  240. versions of the same quantifiers, use (C<??>, C<*?>, C<+?>, C<{}?>).
  241. An example:
  242. $s1 = $s2 = "I am very very cold";
  243. $s1 =~ s/ve.*y //; # I am cold
  244. $s2 =~ s/ve.*?y //; # I am very cold
  245. Notice how the second substitution stopped matching as soon as it
  246. encountered "y ". The C<*?> quantifier effectively tells the regular
  247. expression engine to find a match as quickly as possible and pass
  248. control on to whatever is next in line, like you would if you were
  249. playing hot potato.
  250. =head2 How do I process each word on each line?
  251. Use the split function:
  252. while (<>) {
  253. foreach $word ( split ) {
  254. # do something with $word here
  255. }
  256. }
  257. Note that this isn't really a word in the English sense; it's just
  258. chunks of consecutive non-whitespace characters.
  259. To work with only alphanumeric sequences, you might consider
  260. while (<>) {
  261. foreach $word (m/(\w+)/g) {
  262. # do something with $word here
  263. }
  264. }
  265. =head2 How can I print out a word-frequency or line-frequency summary?
  266. To do this, you have to parse out each word in the input stream. We'll
  267. pretend that by word you mean chunk of alphabetics, hyphens, or
  268. apostrophes, rather than the non-whitespace chunk idea of a word given
  269. in the previous question:
  270. while (<>) {
  271. while ( /(\b[^\W_\d][\w'-]+\b)/g ) { # misses "`sheep'"
  272. $seen{$1}++;
  273. }
  274. }
  275. while ( ($word, $count) = each %seen ) {
  276. print "$count $word\n";
  277. }
  278. If you wanted to do the same thing for lines, you wouldn't need a
  279. regular expression:
  280. while (<>) {
  281. $seen{$_}++;
  282. }
  283. while ( ($line, $count) = each %seen ) {
  284. print "$count $line";
  285. }
  286. If you want these output in a sorted order, see the section on Hashes.
  287. =head2 How can I do approximate matching?
  288. See the module String::Approx available from CPAN.
  289. =head2 How do I efficiently match many regular expressions at once?
  290. The following is extremely inefficient:
  291. # slow but obvious way
  292. @popstates = qw(CO ON MI WI MN);
  293. while (defined($line = <>)) {
  294. for $state (@popstates) {
  295. if ($line =~ /\b$state\b/i) {
  296. print $line;
  297. last;
  298. }
  299. }
  300. }
  301. That's because Perl has to recompile all those patterns for each of
  302. the lines of the file. As of the 5.005 release, there's a much better
  303. approach, one which makes use of the new C<qr//> operator:
  304. # use spiffy new qr// operator, with /i flag even
  305. use 5.005;
  306. @popstates = qw(CO ON MI WI MN);
  307. @poppats = map { qr/\b$_\b/i } @popstates;
  308. while (defined($line = <>)) {
  309. for $patobj (@poppats) {
  310. print $line if $line =~ /$patobj/;
  311. }
  312. }
  313. =head2 Why don't word-boundary searches with C<\b> work for me?
  314. Two common misconceptions are that C<\b> is a synonym for C<\s+>, and
  315. that it's the edge between whitespace characters and non-whitespace
  316. characters. Neither is correct. C<\b> is the place between a C<\w>
  317. character and a C<\W> character (that is, C<\b> is the edge of a
  318. "word"). It's a zero-width assertion, just like C<^>, C<$>, and all
  319. the other anchors, so it doesn't consume any characters. L<perlre>
  320. describes the behaviour of all the regexp metacharacters.
  321. Here are examples of the incorrect application of C<\b>, with fixes:
  322. "two words" =~ /(\w+)\b(\w+)/; # WRONG
  323. "two words" =~ /(\w+)\s+(\w+)/; # right
  324. " =matchless= text" =~ /\b=(\w+)=\b/; # WRONG
  325. " =matchless= text" =~ /=(\w+)=/; # right
  326. Although they may not do what you thought they did, C<\b> and C<\B>
  327. can still be quite useful. For an example of the correct use of
  328. C<\b>, see the example of matching duplicate words over multiple
  329. lines.
  330. An example of using C<\B> is the pattern C<\Bis\B>. This will find
  331. occurrences of "is" on the insides of words only, as in "thistle", but
  332. not "this" or "island".
  333. =head2 Why does using $&, $`, or $' slow my program down?
  334. Because once Perl sees that you need one of these variables anywhere in
  335. the program, it has to provide them on each and every pattern match.
  336. The same mechanism that handles these provides for the use of $1, $2,
  337. etc., so you pay the same price for each regexp that contains capturing
  338. parentheses. But if you never use $&, etc., in your script, then regexps
  339. I<without> capturing parentheses won't be penalized. So avoid $&, $',
  340. and $` if you can, but if you can't, once you've used them at all, use
  341. them at will because you've already paid the price. Remember that some
  342. algorithms really appreciate them. As of the 5.005 release. the $&
  343. variable is no longer "expensive" the way the other two are.
  344. =head2 What good is C<\G> in a regular expression?
  345. The notation C<\G> is used in a match or substitution in conjunction the
  346. C</g> modifier (and ignored if there's no C</g>) to anchor the regular
  347. expression to the point just past where the last match occurred, i.e. the
  348. pos() point. A failed match resets the position of C<\G> unless the
  349. C</c> modifier is in effect.
  350. For example, suppose you had a line of text quoted in standard mail
  351. and Usenet notation, (that is, with leading C<E<gt>> characters), and
  352. you want change each leading C<E<gt>> into a corresponding C<:>. You
  353. could do so in this way:
  354. s/^(>+)/':' x length($1)/gem;
  355. Or, using C<\G>, the much simpler (and faster):
  356. s/\G>/:/g;
  357. A more sophisticated use might involve a tokenizer. The following
  358. lex-like example is courtesy of Jeffrey Friedl. It did not work in
  359. 5.003 due to bugs in that release, but does work in 5.004 or better.
  360. (Note the use of C</c>, which prevents a failed match with C</g> from
  361. resetting the search position back to the beginning of the string.)
  362. while (<>) {
  363. chomp;
  364. PARSER: {
  365. m/ \G( \d+\b )/gcx && do { print "number: $1\n"; redo; };
  366. m/ \G( \w+ )/gcx && do { print "word: $1\n"; redo; };
  367. m/ \G( \s+ )/gcx && do { print "space: $1\n"; redo; };
  368. m/ \G( [^\w\d]+ )/gcx && do { print "other: $1\n"; redo; };
  369. }
  370. }
  371. Of course, that could have been written as
  372. while (<>) {
  373. chomp;
  374. PARSER: {
  375. if ( /\G( \d+\b )/gcx {
  376. print "number: $1\n";
  377. redo PARSER;
  378. }
  379. if ( /\G( \w+ )/gcx {
  380. print "word: $1\n";
  381. redo PARSER;
  382. }
  383. if ( /\G( \s+ )/gcx {
  384. print "space: $1\n";
  385. redo PARSER;
  386. }
  387. if ( /\G( [^\w\d]+ )/gcx {
  388. print "other: $1\n";
  389. redo PARSER;
  390. }
  391. }
  392. }
  393. But then you lose the vertical alignment of the regular expressions.
  394. =head2 Are Perl regexps DFAs or NFAs? Are they POSIX compliant?
  395. While it's true that Perl's regular expressions resemble the DFAs
  396. (deterministic finite automata) of the egrep(1) program, they are in
  397. fact implemented as NFAs (non-deterministic finite automata) to allow
  398. backtracking and backreferencing. And they aren't POSIX-style either,
  399. because those guarantee worst-case behavior for all cases. (It seems
  400. that some people prefer guarantees of consistency, even when what's
  401. guaranteed is slowness.) See the book "Mastering Regular Expressions"
  402. (from O'Reilly) by Jeffrey Friedl for all the details you could ever
  403. hope to know on these matters (a full citation appears in
  404. L<perlfaq2>).
  405. =head2 What's wrong with using grep or map in a void context?
  406. Both grep and map build a return list, regardless of their context.
  407. This means you're making Perl go to the trouble of building up a
  408. return list that you then just ignore. That's no way to treat a
  409. programming language, you insensitive scoundrel!
  410. =head2 How can I match strings with multibyte characters?
  411. This is hard, and there's no good way. Perl does not directly support
  412. wide characters. It pretends that a byte and a character are
  413. synonymous. The following set of approaches was offered by Jeffrey
  414. Friedl, whose article in issue #5 of The Perl Journal talks about this
  415. very matter.
  416. Let's suppose you have some weird Martian encoding where pairs of
  417. ASCII uppercase letters encode single Martian letters (i.e. the two
  418. bytes "CV" make a single Martian letter, as do the two bytes "SG",
  419. "VS", "XX", etc.). Other bytes represent single characters, just like
  420. ASCII.
  421. So, the string of Martian "I am CVSGXX!" uses 12 bytes to encode the
  422. nine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.
  423. Now, say you want to search for the single character C</GX/>. Perl
  424. doesn't know about Martian, so it'll find the two bytes "GX" in the "I
  425. am CVSGXX!" string, even though that character isn't there: it just
  426. looks like it is because "SG" is next to "XX", but there's no real
  427. "GX". This is a big problem.
  428. Here are a few ways, all painful, to deal with it:
  429. $martian =~ s/([A-Z][A-Z])/ $1 /g; # Make sure adjacent ``martian'' bytes
  430. # are no longer adjacent.
  431. print "found GX!\n" if $martian =~ /GX/;
  432. Or like this:
  433. @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;
  434. # above is conceptually similar to: @chars = $text =~ m/(.)/g;
  435. #
  436. foreach $char (@chars) {
  437. print "found GX!\n", last if $char eq 'GX';
  438. }
  439. Or like this:
  440. while ($martian =~ m/\G([A-Z][A-Z]|.)/gs) { # \G probably unneeded
  441. print "found GX!\n", last if $1 eq 'GX';
  442. }
  443. Or like this:
  444. die "sorry, Perl doesn't (yet) have Martian support )-:\n";
  445. There are many double- (and multi-) byte encodings commonly used these
  446. days. Some versions of these have 1-, 2-, 3-, and 4-byte characters,
  447. all mixed.
  448. =head2 How do I match a pattern that is supplied by the user?
  449. Well, if it's really a pattern, then just use
  450. chomp($pattern = <STDIN>);
  451. if ($line =~ /$pattern/) { }
  452. Or, since you have no guarantee that your user entered
  453. a valid regular expression, trap the exception this way:
  454. if (eval { $line =~ /$pattern/ }) { }
  455. But if all you really want to search for a string, not a pattern,
  456. then you should either use the index() function, which is made for
  457. string searching, or if you can't be disabused of using a pattern
  458. match on a non-pattern, then be sure to use C<\Q>...C<\E>, documented
  459. in L<perlre>.
  460. $pattern = <STDIN>;
  461. open (FILE, $input) or die "Couldn't open input $input: $!; aborting";
  462. while (<FILE>) {
  463. print if /\Q$pattern\E/;
  464. }
  465. close FILE;
  466. =head1 AUTHOR AND COPYRIGHT
  467. Copyright (c) 1997-1999 Tom Christiansen and Nathan Torkington.
  468. All rights reserved.
  469. When included as part of the Standard Version of Perl, or as part of
  470. its complete documentation whether printed or otherwise, this work
  471. may be distributed only under the terms of Perl's Artistic Licence.
  472. Any distribution of this file or derivatives thereof I<outside>
  473. of that package require that special arrangements be made with
  474. copyright holder.
  475. Irrespective of its distribution, all code examples in this file
  476. are hereby placed into the public domain. You are permitted and
  477. encouraged to use this code in your own programs for fun
  478. or for profit as you see fit. A simple comment in the code giving
  479. credit would be courteous but is not required.