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.

940 lines
37 KiB

  1. =head1 NAME
  2. perlre - Perl regular expressions
  3. =head1 DESCRIPTION
  4. This page describes the syntax of regular expressions in Perl. For a
  5. description of how to I<use> regular expressions in matching
  6. operations, plus various examples of the same, see discussion
  7. of C<m//>, C<s///>, C<qr//> and C<??> in L<perlop/"Regexp Quote-Like Operators">.
  8. The matching operations can have various modifiers. The modifiers
  9. that relate to the interpretation of the regular expression inside
  10. are listed below. For the modifiers that alter the way a regular expression
  11. is used by Perl, see L<perlop/"Regexp Quote-Like Operators"> and
  12. L<perlop/"Gory details of parsing quoted constructs">.
  13. =over 4
  14. =item i
  15. Do case-insensitive pattern matching.
  16. If C<use locale> is in effect, the case map is taken from the current
  17. locale. See L<perllocale>.
  18. =item m
  19. Treat string as multiple lines. That is, change "^" and "$" from matching
  20. at only the very start or end of the string to the start or end of any
  21. line anywhere within the string,
  22. =item s
  23. Treat string as single line. That is, change "." to match any character
  24. whatsoever, even a newline, which it normally would not match.
  25. The C</s> and C</m> modifiers both override the C<$*> setting. That is, no matter
  26. what C<$*> contains, C</s> without C</m> will force "^" to match only at the
  27. beginning of the string and "$" to match only at the end (or just before a
  28. newline at the end) of the string. Together, as /ms, they let the "." match
  29. any character whatsoever, while yet allowing "^" and "$" to match,
  30. respectively, just after and just before newlines within the string.
  31. =item x
  32. Extend your pattern's legibility by permitting whitespace and comments.
  33. =back
  34. These are usually written as "the C</x> modifier", even though the delimiter
  35. in question might not actually be a slash. In fact, any of these
  36. modifiers may also be embedded within the regular expression itself using
  37. the new C<(?...)> construct. See below.
  38. The C</x> modifier itself needs a little more explanation. It tells
  39. the regular expression parser to ignore whitespace that is neither
  40. backslashed nor within a character class. You can use this to break up
  41. your regular expression into (slightly) more readable parts. The C<#>
  42. character is also treated as a metacharacter introducing a comment,
  43. just as in ordinary Perl code. This also means that if you want real
  44. whitespace or C<#> characters in the pattern (outside of a character
  45. class, where they are unaffected by C</x>), that you'll either have to
  46. escape them or encode them using octal or hex escapes. Taken together,
  47. these features go a long way towards making Perl's regular expressions
  48. more readable. Note that you have to be careful not to include the
  49. pattern delimiter in the comment--perl has no way of knowing you did
  50. not intend to close the pattern early. See the C-comment deletion code
  51. in L<perlop>.
  52. =head2 Regular Expressions
  53. The patterns used in pattern matching are regular expressions such as
  54. those supplied in the Version 8 regex routines. (In fact, the
  55. routines are derived (distantly) from Henry Spencer's freely
  56. redistributable reimplementation of the V8 routines.)
  57. See L<Version 8 Regular Expressions> for details.
  58. In particular the following metacharacters have their standard I<egrep>-ish
  59. meanings:
  60. \ Quote the next metacharacter
  61. ^ Match the beginning of the line
  62. . Match any character (except newline)
  63. $ Match the end of the line (or before newline at the end)
  64. | Alternation
  65. () Grouping
  66. [] Character class
  67. By default, the "^" character is guaranteed to match at only the
  68. beginning of the string, the "$" character at only the end (or before the
  69. newline at the end) and Perl does certain optimizations with the
  70. assumption that the string contains only one line. Embedded newlines
  71. will not be matched by "^" or "$". You may, however, wish to treat a
  72. string as a multi-line buffer, such that the "^" will match after any
  73. newline within the string, and "$" will match before any newline. At the
  74. cost of a little more overhead, you can do this by using the /m modifier
  75. on the pattern match operator. (Older programs did this by setting C<$*>,
  76. but this practice is now deprecated.)
  77. To facilitate multi-line substitutions, the "." character never matches a
  78. newline unless you use the C</s> modifier, which in effect tells Perl to pretend
  79. the string is a single line--even if it isn't. The C</s> modifier also
  80. overrides the setting of C<$*>, in case you have some (badly behaved) older
  81. code that sets it in another module.
  82. The following standard quantifiers are recognized:
  83. * Match 0 or more times
  84. + Match 1 or more times
  85. ? Match 1 or 0 times
  86. {n} Match exactly n times
  87. {n,} Match at least n times
  88. {n,m} Match at least n but not more than m times
  89. (If a curly bracket occurs in any other context, it is treated
  90. as a regular character.) The "*" modifier is equivalent to C<{0,}>, the "+"
  91. modifier to C<{1,}>, and the "?" modifier to C<{0,1}>. n and m are limited
  92. to integral values less than a preset limit defined when perl is built.
  93. This is usually 32766 on the most common platforms. The actual limit can
  94. be seen in the error message generated by code such as this:
  95. $_ **= $_ , / {$_} / for 2 .. 42;
  96. By default, a quantified subpattern is "greedy", that is, it will match as
  97. many times as possible (given a particular starting location) while still
  98. allowing the rest of the pattern to match. If you want it to match the
  99. minimum number of times possible, follow the quantifier with a "?". Note
  100. that the meanings don't change, just the "greediness":
  101. *? Match 0 or more times
  102. +? Match 1 or more times
  103. ?? Match 0 or 1 time
  104. {n}? Match exactly n times
  105. {n,}? Match at least n times
  106. {n,m}? Match at least n but not more than m times
  107. Because patterns are processed as double quoted strings, the following
  108. also work:
  109. \t tab (HT, TAB)
  110. \n newline (LF, NL)
  111. \r return (CR)
  112. \f form feed (FF)
  113. \a alarm (bell) (BEL)
  114. \e escape (think troff) (ESC)
  115. \033 octal char (think of a PDP-11)
  116. \x1B hex char
  117. \c[ control char
  118. \l lowercase next char (think vi)
  119. \u uppercase next char (think vi)
  120. \L lowercase till \E (think vi)
  121. \U uppercase till \E (think vi)
  122. \E end case modification (think vi)
  123. \Q quote (disable) pattern metacharacters till \E
  124. If C<use locale> is in effect, the case map used by C<\l>, C<\L>, C<\u>
  125. and C<\U> is taken from the current locale. See L<perllocale>.
  126. You cannot include a literal C<$> or C<@> within a C<\Q> sequence.
  127. An unescaped C<$> or C<@> interpolates the corresponding variable,
  128. while escaping will cause the literal string C<\$> to be matched.
  129. You'll need to write something like C<m/\Quser\E\@\Qhost/>.
  130. In addition, Perl defines the following:
  131. \w Match a "word" character (alphanumeric plus "_")
  132. \W Match a non-word character
  133. \s Match a whitespace character
  134. \S Match a non-whitespace character
  135. \d Match a digit character
  136. \D Match a non-digit character
  137. A C<\w> matches a single alphanumeric character, not a whole
  138. word. To match a word you'd need to say C<\w+>. If C<use locale> is in
  139. effect, the list of alphabetic characters generated by C<\w> is taken
  140. from the current locale. See L<perllocale>. You may use C<\w>, C<\W>,
  141. C<\s>, C<\S>, C<\d>, and C<\D> within character classes (though not as
  142. either end of a range).
  143. Perl defines the following zero-width assertions:
  144. \b Match a word boundary
  145. \B Match a non-(word boundary)
  146. \A Match only at beginning of string
  147. \Z Match only at end of string, or before newline at the end
  148. \z Match only at end of string
  149. \G Match only where previous m//g left off (works only with /g)
  150. A word boundary (C<\b>) is defined as a spot between two characters that
  151. has a C<\w> on one side of it and a C<\W> on the other side of it (in
  152. either order), counting the imaginary characters off the beginning and
  153. end of the string as matching a C<\W>. (Within character classes C<\b>
  154. represents backspace rather than a word boundary.) The C<\A> and C<\Z> are
  155. just like "^" and "$", except that they won't match multiple times when the
  156. C</m> modifier is used, while "^" and "$" will match at every internal line
  157. boundary. To match the actual end of the string, not ignoring newline,
  158. you can use C<\z>. The C<\G> assertion can be used to chain global
  159. matches (using C<m//g>), as described in
  160. L<perlop/"Regexp Quote-Like Operators">.
  161. It is also useful when writing C<lex>-like scanners, when you have several
  162. patterns that you want to match against consequent substrings of your
  163. string, see the previous reference.
  164. The actual location where C<\G> will match can also be influenced
  165. by using C<pos()> as an lvalue. See L<perlfunc/pos>.
  166. When the bracketing construct C<( ... )> is used, \E<lt>digitE<gt> matches the
  167. digit'th substring. Outside of the pattern, always use "$" instead of "\"
  168. in front of the digit. (While the \E<lt>digitE<gt> notation can on rare occasion work
  169. outside the current pattern, this should not be relied upon. See the
  170. WARNING below.) The scope of $E<lt>digitE<gt> (and C<$`>, C<$&>, and C<$'>)
  171. extends to the end of the enclosing BLOCK or eval string, or to the next
  172. successful pattern match, whichever comes first. If you want to use
  173. parentheses to delimit a subpattern (e.g., a set of alternatives) without
  174. saving it as a subpattern, follow the ( with a ?:.
  175. You may have as many parentheses as you wish. If you have more
  176. than 9 substrings, the variables $10, $11, ... refer to the
  177. corresponding substring. Within the pattern, \10, \11, etc. refer back
  178. to substrings if there have been at least that many left parentheses before
  179. the backreference. Otherwise (for backward compatibility) \10 is the
  180. same as \010, a backspace, and \11 the same as \011, a tab. And so
  181. on. (\1 through \9 are always backreferences.)
  182. C<$+> returns whatever the last bracket match matched. C<$&> returns the
  183. entire matched string. (C<$0> used to return the same thing, but not any
  184. more.) C<$`> returns everything before the matched string. C<$'> returns
  185. everything after the matched string. Examples:
  186. s/^([^ ]*) *([^ ]*)/$2 $1/; # swap first two words
  187. if (/Time: (..):(..):(..)/) {
  188. $hours = $1;
  189. $minutes = $2;
  190. $seconds = $3;
  191. }
  192. Once perl sees that you need one of C<$&>, C<$`> or C<$'> anywhere in
  193. the program, it has to provide them on each and every pattern match.
  194. This can slow your program down. The same mechanism that handles
  195. these provides for the use of $1, $2, etc., so you pay the same price
  196. for each pattern that contains capturing parentheses. But if you never
  197. use $&, etc., in your script, then patterns I<without> capturing
  198. parentheses won't be penalized. So avoid $&, $', and $` if you can,
  199. but if you can't (and some algorithms really appreciate them), once
  200. you've used them once, use them at will, because you've already paid
  201. the price. As of 5.005, $& is not so costly as the other two.
  202. Backslashed metacharacters in Perl are
  203. alphanumeric, such as C<\b>, C<\w>, C<\n>. Unlike some other regular
  204. expression languages, there are no backslashed symbols that aren't
  205. alphanumeric. So anything that looks like \\, \(, \), \E<lt>, \E<gt>,
  206. \{, or \} is always interpreted as a literal character, not a
  207. metacharacter. This was once used in a common idiom to disable or
  208. quote the special meanings of regular expression metacharacters in a
  209. string that you want to use for a pattern. Simply quote all
  210. non-alphanumeric characters:
  211. $pattern =~ s/(\W)/\\$1/g;
  212. Now it is much more common to see either the quotemeta() function or
  213. the C<\Q> escape sequence used to disable all metacharacters' special
  214. meanings like this:
  215. /$unquoted\Q$quoted\E$unquoted/
  216. Perl defines a consistent extension syntax for regular expressions.
  217. The syntax is a pair of parentheses with a question mark as the first
  218. thing within the parentheses (this was a syntax error in older
  219. versions of Perl). The character after the question mark gives the
  220. function of the extension. Several extensions are already supported:
  221. =over 10
  222. =item C<(?#text)>
  223. A comment. The text is ignored. If the C</x> switch is used to enable
  224. whitespace formatting, a simple C<#> will suffice. Note that perl closes
  225. the comment as soon as it sees a C<)>, so there is no way to put a literal
  226. C<)> in the comment.
  227. =item C<(?:pattern)>
  228. =item C<(?imsx-imsx:pattern)>
  229. This is for clustering, not capturing; it groups subexpressions like
  230. "()", but doesn't make backreferences as "()" does. So
  231. @fields = split(/\b(?:a|b|c)\b/)
  232. is like
  233. @fields = split(/\b(a|b|c)\b/)
  234. but doesn't spit out extra fields.
  235. The letters between C<?> and C<:> act as flags modifiers, see
  236. L<C<(?imsx-imsx)>>. In particular,
  237. /(?s-i:more.*than).*million/i
  238. is equivalent to more verbose
  239. /(?:(?s-i)more.*than).*million/i
  240. =item C<(?=pattern)>
  241. A zero-width positive lookahead assertion. For example, C</\w+(?=\t)/>
  242. matches a word followed by a tab, without including the tab in C<$&>.
  243. =item C<(?!pattern)>
  244. A zero-width negative lookahead assertion. For example C</foo(?!bar)/>
  245. matches any occurrence of "foo" that isn't followed by "bar". Note
  246. however that lookahead and lookbehind are NOT the same thing. You cannot
  247. use this for lookbehind.
  248. If you are looking for a "bar" that isn't preceded by a "foo", C</(?!foo)bar/>
  249. will not do what you want. That's because the C<(?!foo)> is just saying that
  250. the next thing cannot be "foo"--and it's not, it's a "bar", so "foobar" will
  251. match. You would have to do something like C</(?!foo)...bar/> for that. We
  252. say "like" because there's the case of your "bar" not having three characters
  253. before it. You could cover that this way: C</(?:(?!foo)...|^.{0,2})bar/>.
  254. Sometimes it's still easier just to say:
  255. if (/bar/ && $` !~ /foo$/)
  256. For lookbehind see below.
  257. =item C<(?E<lt>=pattern)>
  258. A zero-width positive lookbehind assertion. For example, C</(?E<lt>=\t)\w+/>
  259. matches a word following a tab, without including the tab in C<$&>.
  260. Works only for fixed-width lookbehind.
  261. =item C<(?<!pattern)>
  262. A zero-width negative lookbehind assertion. For example C</(?<!bar)foo/>
  263. matches any occurrence of "foo" that isn't following "bar".
  264. Works only for fixed-width lookbehind.
  265. =item C<(?{ code })>
  266. Experimental "evaluate any Perl code" zero-width assertion. Always
  267. succeeds. C<code> is not interpolated. Currently the rules to
  268. determine where the C<code> ends are somewhat convoluted.
  269. The C<code> is properly scoped in the following sense: if the assertion
  270. is backtracked (compare L<"Backtracking">), all the changes introduced after
  271. C<local>isation are undone, so
  272. $_ = 'a' x 8;
  273. m<
  274. (?{ $cnt = 0 }) # Initialize $cnt.
  275. (
  276. a
  277. (?{
  278. local $cnt = $cnt + 1; # Update $cnt, backtracking-safe.
  279. })
  280. )*
  281. aaaa
  282. (?{ $res = $cnt }) # On success copy to non-localized
  283. # location.
  284. >x;
  285. will set C<$res = 4>. Note that after the match $cnt returns to the globally
  286. introduced value 0, since the scopes which restrict C<local> statements
  287. are unwound.
  288. This assertion may be used as L<C<(?(condition)yes-pattern|no-pattern)>>
  289. switch. If I<not> used in this way, the result of evaluation of C<code>
  290. is put into variable $^R. This happens immediately, so $^R can be used from
  291. other C<(?{ code })> assertions inside the same regular expression.
  292. The above assignment to $^R is properly localized, thus the old value of $^R
  293. is restored if the assertion is backtracked (compare L<"Backtracking">).
  294. Due to security concerns, this construction is not allowed if the regular
  295. expression involves run-time interpolation of variables, unless
  296. C<use re 'eval'> pragma is used (see L<re>), or the variables contain
  297. results of qr() operator (see L<perlop/"qr/STRING/imosx">).
  298. This restriction is due to the wide-spread (questionable) practice of
  299. using the construct
  300. $re = <>;
  301. chomp $re;
  302. $string =~ /$re/;
  303. without tainting. While this code is frowned upon from security point
  304. of view, when C<(?{})> was introduced, it was considered bad to add
  305. I<new> security holes to existing scripts.
  306. B<NOTE:> Use of the above insecure snippet without also enabling taint mode
  307. is to be severely frowned upon. C<use re 'eval'> does not disable tainting
  308. checks, thus to allow $re in the above snippet to contain C<(?{})>
  309. I<with tainting enabled>, one needs both C<use re 'eval'> and untaint
  310. the $re.
  311. =item C<(?E<gt>pattern)>
  312. An "independent" subexpression. Matches the substring that a
  313. I<standalone> C<pattern> would match if anchored at the given position,
  314. B<and only this substring>.
  315. Say, C<^(?E<gt>a*)ab> will never match, since C<(?E<gt>a*)> (anchored
  316. at the beginning of string, as above) will match I<all> characters
  317. C<a> at the beginning of string, leaving no C<a> for C<ab> to match.
  318. In contrast, C<a*ab> will match the same as C<a+b>, since the match of
  319. the subgroup C<a*> is influenced by the following group C<ab> (see
  320. L<"Backtracking">). In particular, C<a*> inside C<a*ab> will match
  321. fewer characters than a standalone C<a*>, since this makes the tail match.
  322. An effect similar to C<(?E<gt>pattern)> may be achieved by
  323. (?=(pattern))\1
  324. since the lookahead is in I<"logical"> context, thus matches the same
  325. substring as a standalone C<a+>. The following C<\1> eats the matched
  326. string, thus making a zero-length assertion into an analogue of
  327. C<(?E<gt>...)>. (The difference between these two constructs is that the
  328. second one uses a catching group, thus shifting ordinals of
  329. backreferences in the rest of a regular expression.)
  330. This construct is useful for optimizations of "eternal"
  331. matches, because it will not backtrack (see L<"Backtracking">).
  332. m{ \(
  333. (
  334. [^()]+
  335. |
  336. \( [^()]* \)
  337. )+
  338. \)
  339. }x
  340. That will efficiently match a nonempty group with matching
  341. two-or-less-level-deep parentheses. However, if there is no such group,
  342. it will take virtually forever on a long string. That's because there are
  343. so many different ways to split a long string into several substrings.
  344. This is what C<(.+)+> is doing, and C<(.+)+> is similar to a subpattern
  345. of the above pattern. Consider that the above pattern detects no-match
  346. on C<((()aaaaaaaaaaaaaaaaaa> in several seconds, but that each extra
  347. letter doubles this time. This exponential performance will make it
  348. appear that your program has hung.
  349. However, a tiny modification of this pattern
  350. m{ \(
  351. (
  352. (?> [^()]+ )
  353. |
  354. \( [^()]* \)
  355. )+
  356. \)
  357. }x
  358. which uses C<(?E<gt>...)> matches exactly when the one above does (verifying
  359. this yourself would be a productive exercise), but finishes in a fourth
  360. the time when used on a similar string with 1000000 C<a>s. Be aware,
  361. however, that this pattern currently triggers a warning message under
  362. B<-w> saying it C<"matches the null string many times">):
  363. On simple groups, such as the pattern C<(?E<gt> [^()]+ )>, a comparable
  364. effect may be achieved by negative lookahead, as in C<[^()]+ (?! [^()] )>.
  365. This was only 4 times slower on a string with 1000000 C<a>s.
  366. =item C<(?(condition)yes-pattern|no-pattern)>
  367. =item C<(?(condition)yes-pattern)>
  368. Conditional expression. C<(condition)> should be either an integer in
  369. parentheses (which is valid if the corresponding pair of parentheses
  370. matched), or lookahead/lookbehind/evaluate zero-width assertion.
  371. Say,
  372. m{ ( \( )?
  373. [^()]+
  374. (?(1) \) )
  375. }x
  376. matches a chunk of non-parentheses, possibly included in parentheses
  377. themselves.
  378. =item C<(?imsx-imsx)>
  379. One or more embedded pattern-match modifiers. This is particularly
  380. useful for patterns that are specified in a table somewhere, some of
  381. which want to be case sensitive, and some of which don't. The case
  382. insensitive ones need to include merely C<(?i)> at the front of the
  383. pattern. For example:
  384. $pattern = "foobar";
  385. if ( /$pattern/i ) { }
  386. # more flexible:
  387. $pattern = "(?i)foobar";
  388. if ( /$pattern/ ) { }
  389. Letters after C<-> switch modifiers off.
  390. These modifiers are localized inside an enclosing group (if any). Say,
  391. ( (?i) blah ) \s+ \1
  392. (assuming C<x> modifier, and no C<i> modifier outside of this group)
  393. will match a repeated (I<including the case>!) word C<blah> in any
  394. case.
  395. =back
  396. A question mark was chosen for this and for the new minimal-matching
  397. construct because 1) question mark is pretty rare in older regular
  398. expressions, and 2) whenever you see one, you should stop and "question"
  399. exactly what is going on. That's psychology...
  400. =head2 Backtracking
  401. A fundamental feature of regular expression matching involves the
  402. notion called I<backtracking>, which is currently used (when needed)
  403. by all regular expression quantifiers, namely C<*>, C<*?>, C<+>,
  404. C<+?>, C<{n,m}>, and C<{n,m}?>.
  405. For a regular expression to match, the I<entire> regular expression must
  406. match, not just part of it. So if the beginning of a pattern containing a
  407. quantifier succeeds in a way that causes later parts in the pattern to
  408. fail, the matching engine backs up and recalculates the beginning
  409. part--that's why it's called backtracking.
  410. Here is an example of backtracking: Let's say you want to find the
  411. word following "foo" in the string "Food is on the foo table.":
  412. $_ = "Food is on the foo table.";
  413. if ( /\b(foo)\s+(\w+)/i ) {
  414. print "$2 follows $1.\n";
  415. }
  416. When the match runs, the first part of the regular expression (C<\b(foo)>)
  417. finds a possible match right at the beginning of the string, and loads up
  418. $1 with "Foo". However, as soon as the matching engine sees that there's
  419. no whitespace following the "Foo" that it had saved in $1, it realizes its
  420. mistake and starts over again one character after where it had the
  421. tentative match. This time it goes all the way until the next occurrence
  422. of "foo". The complete regular expression matches this time, and you get
  423. the expected output of "table follows foo."
  424. Sometimes minimal matching can help a lot. Imagine you'd like to match
  425. everything between "foo" and "bar". Initially, you write something
  426. like this:
  427. $_ = "The food is under the bar in the barn.";
  428. if ( /foo(.*)bar/ ) {
  429. print "got <$1>\n";
  430. }
  431. Which perhaps unexpectedly yields:
  432. got <d is under the bar in the >
  433. That's because C<.*> was greedy, so you get everything between the
  434. I<first> "foo" and the I<last> "bar". In this case, it's more effective
  435. to use minimal matching to make sure you get the text between a "foo"
  436. and the first "bar" thereafter.
  437. if ( /foo(.*?)bar/ ) { print "got <$1>\n" }
  438. got <d is under the >
  439. Here's another example: let's say you'd like to match a number at the end
  440. of a string, and you also want to keep the preceding part the match.
  441. So you write this:
  442. $_ = "I have 2 numbers: 53147";
  443. if ( /(.*)(\d*)/ ) { # Wrong!
  444. print "Beginning is <$1>, number is <$2>.\n";
  445. }
  446. That won't work at all, because C<.*> was greedy and gobbled up the
  447. whole string. As C<\d*> can match on an empty string the complete
  448. regular expression matched successfully.
  449. Beginning is <I have 2 numbers: 53147>, number is <>.
  450. Here are some variants, most of which don't work:
  451. $_ = "I have 2 numbers: 53147";
  452. @pats = qw{
  453. (.*)(\d*)
  454. (.*)(\d+)
  455. (.*?)(\d*)
  456. (.*?)(\d+)
  457. (.*)(\d+)$
  458. (.*?)(\d+)$
  459. (.*)\b(\d+)$
  460. (.*\D)(\d+)$
  461. };
  462. for $pat (@pats) {
  463. printf "%-12s ", $pat;
  464. if ( /$pat/ ) {
  465. print "<$1> <$2>\n";
  466. } else {
  467. print "FAIL\n";
  468. }
  469. }
  470. That will print out:
  471. (.*)(\d*) <I have 2 numbers: 53147> <>
  472. (.*)(\d+) <I have 2 numbers: 5314> <7>
  473. (.*?)(\d*) <> <>
  474. (.*?)(\d+) <I have > <2>
  475. (.*)(\d+)$ <I have 2 numbers: 5314> <7>
  476. (.*?)(\d+)$ <I have 2 numbers: > <53147>
  477. (.*)\b(\d+)$ <I have 2 numbers: > <53147>
  478. (.*\D)(\d+)$ <I have 2 numbers: > <53147>
  479. As you see, this can be a bit tricky. It's important to realize that a
  480. regular expression is merely a set of assertions that gives a definition
  481. of success. There may be 0, 1, or several different ways that the
  482. definition might succeed against a particular string. And if there are
  483. multiple ways it might succeed, you need to understand backtracking to
  484. know which variety of success you will achieve.
  485. When using lookahead assertions and negations, this can all get even
  486. tricker. Imagine you'd like to find a sequence of non-digits not
  487. followed by "123". You might try to write that as
  488. $_ = "ABC123";
  489. if ( /^\D*(?!123)/ ) { # Wrong!
  490. print "Yup, no 123 in $_\n";
  491. }
  492. But that isn't going to match; at least, not the way you're hoping. It
  493. claims that there is no 123 in the string. Here's a clearer picture of
  494. why it that pattern matches, contrary to popular expectations:
  495. $x = 'ABC123' ;
  496. $y = 'ABC445' ;
  497. print "1: got $1\n" if $x =~ /^(ABC)(?!123)/ ;
  498. print "2: got $1\n" if $y =~ /^(ABC)(?!123)/ ;
  499. print "3: got $1\n" if $x =~ /^(\D*)(?!123)/ ;
  500. print "4: got $1\n" if $y =~ /^(\D*)(?!123)/ ;
  501. This prints
  502. 2: got ABC
  503. 3: got AB
  504. 4: got ABC
  505. You might have expected test 3 to fail because it seems to a more
  506. general purpose version of test 1. The important difference between
  507. them is that test 3 contains a quantifier (C<\D*>) and so can use
  508. backtracking, whereas test 1 will not. What's happening is
  509. that you've asked "Is it true that at the start of $x, following 0 or more
  510. non-digits, you have something that's not 123?" If the pattern matcher had
  511. let C<\D*> expand to "ABC", this would have caused the whole pattern to
  512. fail.
  513. The search engine will initially match C<\D*> with "ABC". Then it will
  514. try to match C<(?!123> with "123", which of course fails. But because
  515. a quantifier (C<\D*>) has been used in the regular expression, the
  516. search engine can backtrack and retry the match differently
  517. in the hope of matching the complete regular expression.
  518. The pattern really, I<really> wants to succeed, so it uses the
  519. standard pattern back-off-and-retry and lets C<\D*> expand to just "AB" this
  520. time. Now there's indeed something following "AB" that is not
  521. "123". It's in fact "C123", which suffices.
  522. We can deal with this by using both an assertion and a negation. We'll
  523. say that the first part in $1 must be followed by a digit, and in fact, it
  524. must also be followed by something that's not "123". Remember that the
  525. lookaheads are zero-width expressions--they only look, but don't consume
  526. any of the string in their match. So rewriting this way produces what
  527. you'd expect; that is, case 5 will fail, but case 6 succeeds:
  528. print "5: got $1\n" if $x =~ /^(\D*)(?=\d)(?!123)/ ;
  529. print "6: got $1\n" if $y =~ /^(\D*)(?=\d)(?!123)/ ;
  530. 6: got ABC
  531. In other words, the two zero-width assertions next to each other work as though
  532. they're ANDed together, just as you'd use any builtin assertions: C</^$/>
  533. matches only if you're at the beginning of the line AND the end of the
  534. line simultaneously. The deeper underlying truth is that juxtaposition in
  535. regular expressions always means AND, except when you write an explicit OR
  536. using the vertical bar. C</ab/> means match "a" AND (then) match "b",
  537. although the attempted matches are made at different positions because "a"
  538. is not a zero-width assertion, but a one-width assertion.
  539. One warning: particularly complicated regular expressions can take
  540. exponential time to solve due to the immense number of possible ways they
  541. can use backtracking to try match. For example this will take a very long
  542. time to run
  543. /((a{0,5}){0,5}){0,5}/
  544. And if you used C<*>'s instead of limiting it to 0 through 5 matches, then
  545. it would take literally forever--or until you ran out of stack space.
  546. A powerful tool for optimizing such beasts is "independent" groups,
  547. which do not backtrace (see L<C<(?E<gt>pattern)>>). Note also that
  548. zero-length lookahead/lookbehind assertions will not backtrace to make
  549. the tail match, since they are in "logical" context: only the fact
  550. whether they match or not is considered relevant. For an example
  551. where side-effects of a lookahead I<might> have influenced the
  552. following match, see L<C<(?E<gt>pattern)>>.
  553. =head2 Version 8 Regular Expressions
  554. In case you're not familiar with the "regular" Version 8 regex
  555. routines, here are the pattern-matching rules not described above.
  556. Any single character matches itself, unless it is a I<metacharacter>
  557. with a special meaning described here or above. You can cause
  558. characters that normally function as metacharacters to be interpreted
  559. literally by prefixing them with a "\" (e.g., "\." matches a ".", not any
  560. character; "\\" matches a "\"). A series of characters matches that
  561. series of characters in the target string, so the pattern C<blurfl>
  562. would match "blurfl" in the target string.
  563. You can specify a character class, by enclosing a list of characters
  564. in C<[]>, which will match any one character from the list. If the
  565. first character after the "[" is "^", the class matches any character not
  566. in the list. Within a list, the "-" character is used to specify a
  567. range, so that C<a-z> represents all characters between "a" and "z",
  568. inclusive. If you want "-" itself to be a member of a class, put it
  569. at the start or end of the list, or escape it with a backslash. (The
  570. following all specify the same class of three characters: C<[-az]>,
  571. C<[az-]>, and C<[a\-z]>. All are different from C<[a-z]>, which
  572. specifies a class containing twenty-six characters.)
  573. Note also that the whole range idea is rather unportable between
  574. character sets--and even within character sets they may cause results
  575. you probably didn't expect. A sound principle is to use only ranges
  576. that begin from and end at either alphabets of equal case ([a-e],
  577. [A-E]), or digits ([0-9]). Anything else is unsafe. If in doubt,
  578. spell out the character sets in full.
  579. Characters may be specified using a metacharacter syntax much like that
  580. used in C: "\n" matches a newline, "\t" a tab, "\r" a carriage return,
  581. "\f" a form feed, etc. More generally, \I<nnn>, where I<nnn> is a string
  582. of octal digits, matches the character whose ASCII value is I<nnn>.
  583. Similarly, \xI<nn>, where I<nn> are hexadecimal digits, matches the
  584. character whose ASCII value is I<nn>. The expression \cI<x> matches the
  585. ASCII character control-I<x>. Finally, the "." metacharacter matches any
  586. character except "\n" (unless you use C</s>).
  587. You can specify a series of alternatives for a pattern using "|" to
  588. separate them, so that C<fee|fie|foe> will match any of "fee", "fie",
  589. or "foe" in the target string (as would C<f(e|i|o)e>). The
  590. first alternative includes everything from the last pattern delimiter
  591. ("(", "[", or the beginning of the pattern) up to the first "|", and
  592. the last alternative contains everything from the last "|" to the next
  593. pattern delimiter. For this reason, it's common practice to include
  594. alternatives in parentheses, to minimize confusion about where they
  595. start and end.
  596. Alternatives are tried from left to right, so the first
  597. alternative found for which the entire expression matches, is the one that
  598. is chosen. This means that alternatives are not necessarily greedy. For
  599. example: when matching C<foo|foot> against "barefoot", only the "foo"
  600. part will match, as that is the first alternative tried, and it successfully
  601. matches the target string. (This might not seem important, but it is
  602. important when you are capturing matched text using parentheses.)
  603. Also remember that "|" is interpreted as a literal within square brackets,
  604. so if you write C<[fee|fie|foe]> you're really only matching C<[feio|]>.
  605. Within a pattern, you may designate subpatterns for later reference by
  606. enclosing them in parentheses, and you may refer back to the I<n>th
  607. subpattern later in the pattern using the metacharacter \I<n>.
  608. Subpatterns are numbered based on the left to right order of their
  609. opening parenthesis. A backreference matches whatever
  610. actually matched the subpattern in the string being examined, not the
  611. rules for that subpattern. Therefore, C<(0|0x)\d*\s\1\d*> will
  612. match "0x1234 0x4321", but not "0x1234 01234", because subpattern 1
  613. actually matched "0x", even though the rule C<0|0x> could
  614. potentially match the leading 0 in the second number.
  615. =head2 WARNING on \1 vs $1
  616. Some people get too used to writing things like:
  617. $pattern =~ s/(\W)/\\\1/g;
  618. This is grandfathered for the RHS of a substitute to avoid shocking the
  619. B<sed> addicts, but it's a dirty habit to get into. That's because in
  620. PerlThink, the righthand side of a C<s///> is a double-quoted string. C<\1> in
  621. the usual double-quoted string means a control-A. The customary Unix
  622. meaning of C<\1> is kludged in for C<s///>. However, if you get into the habit
  623. of doing that, you get yourself into trouble if you then add an C</e>
  624. modifier.
  625. s/(\d+)/ \1 + 1 /eg; # causes warning under -w
  626. Or if you try to do
  627. s/(\d+)/\1000/;
  628. You can't disambiguate that by saying C<\{1}000>, whereas you can fix it with
  629. C<${1}000>. Basically, the operation of interpolation should not be confused
  630. with the operation of matching a backreference. Certainly they mean two
  631. different things on the I<left> side of the C<s///>.
  632. =head2 Repeated patterns matching zero-length substring
  633. WARNING: Difficult material (and prose) ahead. This section needs a rewrite.
  634. Regular expressions provide a terse and powerful programming language. As
  635. with most other power tools, power comes together with the ability
  636. to wreak havoc.
  637. A common abuse of this power stems from the ability to make infinite
  638. loops using regular expressions, with something as innocuous as:
  639. 'foo' =~ m{ ( o? )* }x;
  640. The C<o?> can match at the beginning of C<'foo'>, and since the position
  641. in the string is not moved by the match, C<o?> would match again and again
  642. due to the C<*> modifier. Another common way to create a similar cycle
  643. is with the looping modifier C<//g>:
  644. @matches = ( 'foo' =~ m{ o? }xg );
  645. or
  646. print "match: <$&>\n" while 'foo' =~ m{ o? }xg;
  647. or the loop implied by split().
  648. However, long experience has shown that many programming tasks may
  649. be significantly simplified by using repeated subexpressions which
  650. may match zero-length substrings, with a simple example being:
  651. @chars = split //, $string; # // is not magic in split
  652. ($whitewashed = $string) =~ s/()/ /g; # parens avoid magic s// /
  653. Thus Perl allows the C</()/> construct, which I<forcefully breaks
  654. the infinite loop>. The rules for this are different for lower-level
  655. loops given by the greedy modifiers C<*+{}>, and for higher-level
  656. ones like the C</g> modifier or split() operator.
  657. The lower-level loops are I<interrupted> when it is detected that a
  658. repeated expression did match a zero-length substring, thus
  659. m{ (?: NON_ZERO_LENGTH | ZERO_LENGTH )* }x;
  660. is made equivalent to
  661. m{ (?: NON_ZERO_LENGTH )*
  662. |
  663. (?: ZERO_LENGTH )?
  664. }x;
  665. The higher level-loops preserve an additional state between iterations:
  666. whether the last match was zero-length. To break the loop, the following
  667. match after a zero-length match is prohibited to have a length of zero.
  668. This prohibition interacts with backtracking (see L<"Backtracking">),
  669. and so the I<second best> match is chosen if the I<best> match is of
  670. zero length.
  671. Say,
  672. $_ = 'bar';
  673. s/\w??/<$&>/g;
  674. results in C<"<><b><><a><><r><>">. At each position of the string the best
  675. match given by non-greedy C<??> is the zero-length match, and the I<second
  676. best> match is what is matched by C<\w>. Thus zero-length matches
  677. alternate with one-character-long matches.
  678. Similarly, for repeated C<m/()/g> the second-best match is the match at the
  679. position one notch further in the string.
  680. The additional state of being I<matched with zero-length> is associated to
  681. the matched string, and is reset by each assignment to pos().
  682. =head2 Creating custom RE engines
  683. Overloaded constants (see L<overload>) provide a simple way to extend
  684. the functionality of the RE engine.
  685. Suppose that we want to enable a new RE escape-sequence C<\Y|> which
  686. matches at boundary between white-space characters and non-whitespace
  687. characters. Note that C<(?=\S)(?<!\S)|(?!\S)(?<=\S)> matches exactly
  688. at these positions, so we want to have each C<\Y|> in the place of the
  689. more complicated version. We can create a module C<customre> to do
  690. this:
  691. package customre;
  692. use overload;
  693. sub import {
  694. shift;
  695. die "No argument to customre::import allowed" if @_;
  696. overload::constant 'qr' => \&convert;
  697. }
  698. sub invalid { die "/$_[0]/: invalid escape '\\$_[1]'"}
  699. my %rules = ( '\\' => '\\',
  700. 'Y|' => qr/(?=\S)(?<!\S)|(?!\S)(?<=\S)/ );
  701. sub convert {
  702. my $re = shift;
  703. $re =~ s{
  704. \\ ( \\ | Y . )
  705. }
  706. { $rules{$1} or invalid($re,$1) }sgex;
  707. return $re;
  708. }
  709. Now C<use customre> enables the new escape in constant regular
  710. expressions, i.e., those without any runtime variable interpolations.
  711. As documented in L<overload>, this conversion will work only over
  712. literal parts of regular expressions. For C<\Y|$re\Y|> the variable
  713. part of this regular expression needs to be converted explicitly
  714. (but only if the special meaning of C<\Y|> should be enabled inside $re):
  715. use customre;
  716. $re = <>;
  717. chomp $re;
  718. $re = customre::convert $re;
  719. /\Y|$re\Y|/;
  720. =head2 SEE ALSO
  721. L<perlop/"Regexp Quote-Like Operators">.
  722. L<perlop/"Gory details of parsing quoted constructs">.
  723. L<perlfunc/pos>.
  724. L<perllocale>.
  725. I<Mastering Regular Expressions> (see L<perlbook>) by Jeffrey Friedl.