home *** CD-ROM | disk | FTP | other *** search
/ ARM Club 3 / TheARMClub_PDCD3.iso / programs / comms_networking / zonk / rawdocs / regex < prev    next >
Encoding:
Text File  |  1999-02-13  |  42.3 KB  |  942 lines

  1. $zonkpage 1.07
  2.  
  3. $usetemplate: tpl.pcre/tpl
  4.  
  5. title: Appendix C - Perl-Compatible Regular Expressions (PCRE)
  6.  
  7. text:{<sh>Introduction</sh>
  8.  
  9. Regular expressions can look daunting the first time you come across them. All the brackets, question marks, dots and asterisks have a tendency to baffle. However they are very powerful, particularly so in this implementation and it is worth taking the time to understand them.
  10.  
  11. <sh>Contents</sh>
  12.  
  13. <ul>
  14. <li><a href="#limi">Limitations</a>
  15. <li><a href="#diff">Differences from Perl</a>
  16. <li><a href="#regd">Regular expression details</a>
  17. <li><a href="#bacs">Backslash (\)</a>
  18. <li><a href="#circ">Circumflex (^) and Dollar ($)</a>
  19. <li><a href="#full">Full stop (.)</a>
  20. <li><a href="#squa">Square brackets ([])</a>
  21. <li><a href="#virt">Vertical bar (|)</a>
  22. <li><a href="#opts">Internal option setting</a>
  23. <li><a href="#subs">Subpatterns</a>
  24. <li><a href="#repi">Repetition</a>
  25. <li><a href="#bacr">Back references</a>
  26. <li><a href="#asrt">Assertions</a>
  27. <li><a href="#once">Once-only subpatterns</a>
  28. <li><a href="#cond">Conditional subpatterns</a>
  29. <li><a href="#comm">Comments</a>
  30. <li><a href="#perf">Performance</a>
  31. </ul>
  32.  
  33.  
  34. <sh>Acknowledgement</sh>
  35.  
  36. Zonk uses PCRE code (version 2.02) made freely available by <b>Philip Hazel</b>. The PCRE distribution package can be found at <a href="ftp://ftp.cus.cam.ac.uk/pub/software/programs/pcre/">ftp://ftp.cus.cam.ac.uk/pub/software/programs/pcre/</a> The information below is extracted from his documentation. In it there are certain references to options which may be set when the PCRE routines are called. As there is no direct access to these routines via Zonk these options all have their default value apart from PCRE_CASELESS (ignore case when matching) which Zonk always sets. You can however reset these options from within a pattern using <a href="#opts">internal option settings</a> 
  37.  
  38. <a name="limi"></a><sh>LIMITATIONS</sh>
  39.  
  40. There are some size limitations in PCRE but it is hoped that they will never in
  41. practice be relevant.
  42. The maximum length of a compiled pattern is 65539 (sic) bytes.
  43. All values in repeating quantifiers must be less than 65536.
  44. The maximum number of capturing subpatterns is 99 [Zonk only allows access to the first 9].
  45. The maximum number of all parenthesized subpatterns, including capturing
  46. subpatterns, assertions, and other types of subpattern, is 200.
  47.  
  48. The maximum length of a subject string is the largest positive number that an
  49. integer variable can hold. However, PCRE uses recursion to handle subpatterns
  50. and indefinite repetition. This means that the available stack space may limit
  51. the size of a subject string that can be processed by certain patterns.
  52.  
  53.  
  54. <a name="diff"></a><sh>DIFFERENCES FROM PERL</sh>
  55.  
  56. The differences described here are with respect to Perl 5.005.
  57.  
  58. 1. By default, a whitespace character is any character that the C library
  59. function <b>isspace()</b> recognizes, though it is possible to compile PCRE with
  60. alternative character type tables. Normally <b>isspace()</b> matches space,
  61. formfeed, newline, carriage return, horizontal tab, and vertical tab. Perl 5
  62. no longer includes vertical tab in its set of whitespace characters. The \v
  63. escape that was in the Perl documentation for a long time was never in fact
  64. recognized. However, the character itself was treated as whitespace at least
  65. up to 5.002. In 5.004 and 5.005 it does not match \s.
  66.  
  67. 2. PCRE does not allow repeat quantifiers on lookahead assertions. Perl permits
  68. them, but they do not mean what you might think. For example, (?!a){3} does
  69. not assert that the next three characters are not "a". It just asserts that the
  70. next character is not "a" three times.
  71.  
  72. 3. Capturing subpatterns that occur inside negative lookahead assertions are
  73. counted, but their entries in the offsets vector are never set. Perl sets its
  74. numerical variables from any such patterns that are matched before the
  75. assertion fails to match something (thereby succeeding), but only if the
  76. negative lookahead assertion contains just one branch.
  77.  
  78. 4. Though binary zero characters are supported in the subject string, they are
  79. not allowed in a pattern string because it is passed as a normal C string,
  80. terminated by zero. The escape sequence "\0" can be used in the pattern to
  81. represent a binary zero.
  82.  
  83. 5. The following Perl escape sequences are not supported: \l, \u, \L, \U,
  84. \E, \Q. In fact these are implemented by Perl's general string-handling and
  85. are not part of its pattern matching engine.
  86.  
  87. 6. The Perl \G assertion is not supported as it is not relevant to single
  88. pattern matches.
  89.  
  90. 7. Fairly obviously, PCRE does not support the (?{code}) construction.
  91.  
  92. 8. There are at the time of writing some oddities in Perl 5.005_02 concerned
  93. with the settings of captured strings when part of a pattern is repeated. For
  94. example, matching "aba" against the pattern /^(a(b)?)+$/ sets $2 to the value
  95. "b", but matching "aabbaa" against /^(aa(bb)?)+$/ leaves $2 unset. However, if
  96. the pattern is changed to /^(aa(b(b))?)+$/ then $2 (and $3) get set.
  97.  
  98. In Perl 5.004 $2 is set in both cases, and that is also true of PCRE. If in the
  99. future Perl changes to a consistent state that is different, PCRE may change to
  100. follow.
  101.  
  102. 9. Another as yet unresolved discrepancy is that in Perl 5.005_02 the pattern
  103. /^(a)?(?(1)a|b)+$/ matches the string "a", whereas in PCRE it does not.
  104. However, in both Perl and PCRE /^(a)?a/ matched against "a" leaves $1 unset.
  105.  
  106. 10. PCRE provides some extensions to the Perl regular expression facilities:
  107.  
  108. (a) Although lookbehind assertions must match fixed length strings, each
  109. alternative branch of a lookbehind assertion can match a different length of
  110. string. Perl 5.005 requires them all to have the same length.
  111.  
  112. (b) If PCRE_DOLLAR_ENDONLY is set and PCRE_MULTILINE is not set, the $ meta-
  113. character matches only at the very end of the string.
  114.  
  115. (c) If PCRE_EXTRA is set, a backslash followed by a letter with no special
  116. meaning is faulted.
  117.  
  118. (d) If PCRE_UNGREEDY is set, the greediness of the repetition quantifiers is
  119. inverted, that is, by default they are not greedy, but if followed by a
  120. question mark they are.
  121.  
  122.  
  123. <a name="regd"></a><sh>REGULAR EXPRESSION DETAILS</sh>
  124. The syntax and semantics of the regular expressions supported by PCRE are
  125. described below. Regular expressions are also described in the Perl
  126. documentation and in a number of other books, some of which have copious
  127. examples. Jeffrey Friedl's "Mastering Regular Expressions", published by
  128. O'Reilly (ISBN 1-56592-257-3), covers them in great detail. The description
  129. here is intended as reference documentation.
  130.  
  131. A regular expression is a pattern that is matched against a subject string from
  132. left to right. Most characters stand for themselves in a pattern, and match the
  133. corresponding characters in the subject. As a trivial example, the pattern
  134.  
  135.   The quick brown fox
  136.  
  137. matches a portion of a subject string that is identical to itself. The power of
  138. regular expressions comes from the ability to include alternatives and
  139. repetitions in the pattern. These are encoded in the pattern by the use of
  140. <i>meta-characters</i>, which do not stand for themselves but instead are
  141. interpreted in some special way.
  142.  
  143. There are two different sets of meta-characters: those that are recognized
  144. anywhere in the pattern except within square brackets, and those that are
  145. recognized in square brackets. Outside square brackets, the meta-characters are
  146. as follows:
  147.  
  148. <pre>
  149.   \      general escape character with several uses
  150.   ^      assert start of subject (or line, in multiline mode)
  151.   $      assert end of subject (or line, in multiline mode)
  152.   .      match any character except newline (by default)
  153.   [      start character class definition
  154.   |      start of alternative branch
  155.   (      start subpattern
  156.   )      end subpattern
  157.   ?      extends the meaning of (
  158.          also 0 or 1 quantifier
  159.          also quantifier minimizer
  160.   *      0 or more quantifier
  161.   +      1 or more quantifier
  162.   {      start min/max quantifier
  163. </pre>
  164.  
  165. Part of a pattern that is in square brackets is called a "character class". In
  166. a character class the only meta-characters are:
  167.  
  168. <pre>
  169.   \      general escape character
  170.   ^      negate the class, but only if the first character
  171.   -      indicates character range
  172.   ]      terminates the character class
  173. </pre>
  174.  
  175. The following sections describe the use of each of the meta-characters.
  176.  
  177.  
  178. <a name="bacs"></a><sh>BACKSLASH</sh>
  179. The backslash character has several uses. Firstly, if it is followed by a
  180. non-alphameric character, it takes away any special meaning that character may
  181. have. This use of backslash as an escape character applies both inside and
  182. outside character classes.
  183.  
  184. For example, if you want to match a "*" character, you write "\*" in the
  185. pattern. This applies whether or not the following character would otherwise be
  186. interpreted as a meta-character, so it is always safe to precede a
  187. non-alphameric with "\" to specify that it stands for itself. In particular,
  188. if you want to match a backslash, you write "\\".
  189.  
  190. If a pattern is compiled with the PCRE_EXTENDED option, whitespace in the
  191. pattern (other than in a character class) and characters between a "#" outside
  192. a character class and the next newline character are ignored. An escaping
  193. backslash can be used to include a whitespace or "#" character as part of the
  194. pattern.
  195.  
  196. A second use of backslash provides a way of encoding non-printing characters
  197. in patterns in a visible manner. There is no restriction on the appearance of
  198. non-printing characters, apart from the binary zero that terminates a pattern,
  199. but when a pattern is being prepared by text editing, it is usually easier to
  200. use one of the following escape sequences than the binary character it
  201. represents:
  202.  
  203. <pre>
  204.   \a     alarm, that is, the BEL character (hex 07)
  205.   \cx    "control-x", where x is any character
  206.   \e     escape (hex 1B)
  207.   \f     formfeed (hex 0C)
  208.   \n     newline (hex 0A)
  209.   \r     carriage return (hex 0D)
  210.   \t     tab (hex 09)
  211.   \xhh   character with hex code hh
  212.   \ddd   character with octal code ddd, or backreference
  213. </pre>
  214.  
  215. The precise effect of "\cx" is as follows: if "x" is a lower case letter, it
  216. is converted to upper case. Then bit 6 of the character (hex 40) is inverted.
  217. Thus "\cz" becomes hex 1A, but "\c{" becomes hex 3B, while "\c;" becomes hex
  218. 7B.
  219.  
  220. After "\x", up to two hexadecimal digits are read (letters can be in upper or
  221. lower case).
  222.  
  223. After "\0" up to two further octal digits are read. In both cases, if there
  224. are fewer than two digits, just those that are present are used. Thus the
  225. sequence "\0\x\07" specifies two binary zeros followed by a BEL character.
  226. Make sure you supply two digits after the initial zero if the character that
  227. follows is itself an octal digit.
  228.  
  229. The handling of a backslash followed by a digit other than 0 is complicated.
  230. Outside a character class, PCRE reads it and any following digits as a decimal
  231. number. If the number is less than 10, or if there have been at least that many
  232. previous capturing left parentheses in the expression, the entire sequence is
  233. taken as a <i>back reference</i>. A description of how this works is given
  234. later, following the discussion of parenthesized subpatterns.
  235.  
  236. Inside a character class, or if the decimal number is greater than 9 and there
  237. have not been that many capturing subpatterns, PCRE re-reads up to three octal
  238. digits following the backslash, and generates a single byte from the least
  239. significant 8 bits of the value. Any subsequent digits stand for themselves.
  240. For example:
  241.  
  242. <pre>
  243.   \040   is another way of writing a space
  244.   \40    is the same, provided there are fewer than 40
  245.             previous capturing subpatterns
  246.   \7     is always a back reference
  247.   \11    might be a back reference, or another way of
  248.             writing a tab
  249.   \011   is always a tab
  250.   \0113  is a tab followed by the character "3"
  251.   \113   is the character with octal code 113 (since there
  252.             can be no more than 99 back references)
  253.   \377   is a byte consisting entirely of 1 bits
  254.   \81    is either a back reference, or a binary zero
  255.             followed by the two characters "8" and "1"
  256. </pre>
  257.  
  258. Note that octal values of 100 or greater must not be introduced by a leading
  259. zero, because no more than three octal digits are ever read.
  260.  
  261. All the sequences that define a single byte value can be used both inside and
  262. outside character classes. In addition, inside a character class, the sequence
  263. "\b" is interpreted as the backspace character (hex 08). Outside a character
  264. class it has a different meaning (see below).
  265.  
  266. The third use of backslash is for specifying generic character types:
  267.  
  268. <pre>
  269.   \d     any decimal digit
  270.   \D     any character that is not a decimal digit
  271.   \s     any whitespace character
  272.   \S     any character that is not a whitespace character
  273.   \w     any "word" character
  274.   \W     any "non-word" character
  275. </pre>
  276.  
  277. Each pair of escape sequences partitions the complete set of characters into
  278. two disjoint sets. Any given character matches one, and only one, of each pair.
  279.  
  280. A "word" character is any letter or digit or the underscore character, that is,
  281. any character which can be part of a Perl "word". The definition of letters and
  282. digits is controlled by PCRE's character tables, and may vary if locale-
  283. specific matching is taking place (see "Locale support" above). For example, in
  284. the "fr" (French) locale, some character codes greater than 128 are used for
  285. accented letters, and these are matched by \w.
  286.  
  287. These character type sequences can appear both inside and outside character
  288. classes. They each match one character of the appropriate type. If the current
  289. matching point is at the end of the subject string, all of them fail, since
  290. there is no character to match.
  291.  
  292. The fourth use of backslash is for certain simple assertions. An assertion
  293. specifies a condition that has to be met at a particular point in a match,
  294. without consuming any characters from the subject string. The use of
  295. subpatterns for more complicated assertions is described below. The backslashed
  296. assertions are
  297.  
  298. <pre>
  299.   \b     word boundary
  300.   \B     not a word boundary
  301.   \A     start of subject (independent of multiline mode)
  302.   \Z     end of subject or newline at end (independent of multiline mode)
  303.   \z     end of subject (independent of multiline mode)
  304. </pre>  
  305.  
  306. These assertions may not appear in character classes (but note that "\b" has a
  307. different meaning, namely the backspace character, inside a character class).
  308.  
  309. A word boundary is a position in the subject string where the current character
  310. and the previous character do not both match \w or \W (i.e. one matches
  311. \w and the other matches \W), or the start or end of the string if the
  312. first or last character matches \w, respectively.
  313.  
  314. The \A, \Z, and \z assertions differ from the traditional circumflex and
  315. dollar (described below) in that they only ever match at the very start and end
  316. of the subject string, whatever options are set. They are not affected by the
  317. PCRE_NOTBOL or PCRE_NOTEOL options. The difference between \Z and \z is that
  318. \Z matches before a newline that is the last character of the string as well
  319. as at the end of the string, whereas \z matches only at the end.
  320.  
  321.  
  322. <a name="circ"></a><sh>CIRCUMFLEX AND DOLLAR</sh>
  323. Outside a character class, in the default matching mode, the circumflex
  324. character is an assertion which is true only if the current matching point is
  325. at the start of the subject string. Inside a character class, circumflex has an
  326. entirely different meaning (see below).
  327.  
  328. Circumflex need not be the first character of the pattern if a number of
  329. alternatives are involved, but it should be the first thing in each alternative
  330. in which it appears if the pattern is ever to match that branch. If all
  331. possible alternatives start with a circumflex, that is, if the pattern is
  332. constrained to match only at the start of the subject, it is said to be an
  333. "anchored" pattern. (There are also other constructs that can cause a pattern
  334. to be anchored.)
  335.  
  336. A dollar character is an assertion which is true only if the current matching
  337. point is at the end of the subject string, or immediately before a newline
  338. character that is the last character in the string (by default). Dollar need
  339. not be the last character of the pattern if a number of alternatives are
  340. involved, but it should be the last item in any branch in which it appears.
  341. Dollar has no special meaning in a character class.
  342.  
  343. The meaning of dollar can be changed so that it matches only at the very end of
  344. the string, by setting the PCRE_DOLLAR_ENDONLY option at compile or matching
  345. time. This does not affect the \Z assertion.
  346.  
  347. The meanings of the circumflex and dollar characters are changed if the
  348. PCRE_MULTILINE option is set. When this is the case, they match immediately
  349. after and immediately before an internal "\n" character, respectively, in
  350. addition to matching at the start and end of the subject string. For example,
  351. the pattern /^abc$/ matches the subject string "def\nabc" in multiline mode,
  352. but not otherwise. Consequently, patterns that are anchored in single line mode
  353. because all branches start with "^" are not anchored in multiline mode. The
  354. PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is set.
  355.  
  356. Note that the sequences \A, \Z, and \z can be used to match the start and
  357. end of the subject in both modes, and if all branches of a pattern start with
  358. \A is it always anchored, whether PCRE_MULTILINE is set or not.
  359.  
  360.  
  361. <a name="full"></a><sh>FULL STOP (PERIOD, DOT)</sh>
  362. Outside a character class, a dot in the pattern matches any one character in
  363. the subject, including a non-printing character, but not (by default) newline.
  364. If the PCRE_DOTALL option is set, then dots match newlines as well. The
  365. handling of dot is entirely independent of the handling of circumflex and
  366. dollar, the only relationship being that they both involve newline characters.
  367. Dot has no special meaning in a character class.
  368.  
  369.  
  370. <a name="squa"></a><sh>SQUARE BRACKETS</sh>
  371. An opening square bracket introduces a character class, terminated by a closing
  372. square bracket. A closing square bracket on its own is not special. If a
  373. closing square bracket is required as a member of the class, it should be the
  374. first data character in the class (after an initial circumflex, if present) or
  375. escaped with a backslash.
  376.  
  377. A character class matches a single character in the subject; the character must
  378. be in the set of characters defined by the class, unless the first character in
  379. the class is a circumflex, in which case the subject character must not be in
  380. the set defined by the class. If a circumflex is actually required as a member
  381. of the class, ensure it is not the first character, or escape it with a
  382. backslash.
  383.  
  384. For example, the character class [aeiou] matches any lower case vowel, while
  385. [^aeiou] matches any character that is not a lower case vowel. Note that a
  386. circumflex is just a convenient notation for specifying the characters which
  387. are in the class by enumerating those that are not. It is not an assertion: it
  388. still consumes a character from the subject string, and fails if the current
  389. pointer is at the end of the string.
  390.  
  391. When caseless matching is set, any letters in a class represent both their
  392. upper case and lower case versions, so for example, a caseless [aeiou] matches
  393. "A" as well as "a", and a caseless [^aeiou] does not match "A", whereas a
  394. caseful version would.
  395.  
  396. The newline character is never treated in any special way in character classes,
  397. whatever the setting of the PCRE_DOTALL or PCRE_MULTILINE options is. A class
  398. such as [^a] will always match a newline.
  399.  
  400. The minus (hyphen) character can be used to specify a range of characters in a
  401. character class. For example, [d-m] matches any letter between d and m,
  402. inclusive. If a minus character is required in a class, it must be escaped with
  403. a backslash or appear in a position where it cannot be interpreted as
  404. indicating a range, typically as the first or last character in the class. It
  405. is not possible to have the character "]" as the end character of a range,
  406. since a sequence such as [w-] is interpreted as a class of two characters. The
  407. octal or hexadecimal representation of "]" can, however, be used to end a
  408. range.
  409.  
  410. Ranges operate in ASCII collating sequence. They can also be used for
  411. characters specified numerically, for example [\000-\037]. If a range that
  412. includes letters is used when caseless matching is set, it matches the letters
  413. in either case. For example, [W-c] is equivalent to [][\^_`wxyzabc], matched
  414. caselessly, and if character tables for the "fr" locale are in use,
  415. [\xc8-\xcb] matches accented E characters in both cases.
  416.  
  417. The character types \d, \D, \s, \S, \w, and \W may also appear in a
  418. character class, and add the characters that they match to the class. For
  419. example, [\dABCDEF] matches any hexadecimal digit. A circumflex can
  420. conveniently be used with the upper case character types to specify a more
  421. restricted set of characters than the matching lower case type. For example,
  422. the class [^\W_] matches any letter or digit, but not underscore.
  423.  
  424. All non-alphameric characters other than \, -, ^ (at the start) and the
  425. terminating ] are non-special in character classes, but it does no harm if they
  426. are escaped.
  427.  
  428.  
  429. <a name="virt"></a><sh>VERTICAL BAR</sh>
  430. Vertical bar characters are used to separate alternative patterns. For example,
  431. the pattern
  432.  
  433.   gilbert|sullivan
  434.  
  435. matches either "gilbert" or "sullivan". Any number of alternatives may appear,
  436. and an empty alternative is permitted (matching the empty string).
  437. The matching process tries each alternative in turn, from left to right,
  438. and the first one that succeeds is used. If the alternatives are within a
  439. subpattern (defined below), "succeeds" means matching the rest of the main
  440. pattern as well as the alternative in the subpattern.
  441.  
  442.  
  443. <a name="opts"></a><sh>INTERNAL OPTION SETTING</sh>
  444. The settings of PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL, and PCRE_EXTENDED
  445. can be changed from within the pattern by a sequence of Perl option letters
  446. enclosed between "(?" and ")". The option letters are
  447.  
  448. <pre>
  449.   i  for PCRE_CASELESS
  450.   m  for PCRE_MULTILINE
  451.   s  for PCRE_DOTALL
  452.   x  for PCRE_EXTENDED
  453. </pre>
  454.  
  455. For example, (?im) sets caseless, multiline matching. It is also possible to
  456. unset these options by preceding the letter with a hyphen, and a combined
  457. setting and unsetting such as (?im-sx), which sets PCRE_CASELESS and
  458. PCRE_MULTILINE while unsetting PCRE_DOTALL and PCRE_EXTENDED, is also
  459. permitted. If a letter appears both before and after the hyphen, the option is
  460. unset.
  461.  
  462. The scope of these option changes depends on where in the pattern the setting
  463. occurs. For settings that are outside any subpattern (defined below), the
  464. effect is the same as if the options were set or unset at the start of
  465. matching. The following patterns all behave in exactly the same way:
  466.  
  467.   (?i)abc
  468.   a(?i)bc
  469.   ab(?i)c
  470.   abc(?i)
  471.  
  472. which in turn is the same as compiling the pattern abc with PCRE_CASELESS set.
  473. In other words, such "top level" settings apply to the whole pattern (unless
  474. there are other changes inside subpatterns). If there is more than one setting
  475. of the same option at top level, the rightmost setting is used.
  476.  
  477. If an option change occurs inside a subpattern, the effect is different. This
  478. is a change of behaviour in Perl 5.005. An option change inside a subpattern
  479. affects only that part of the subpattern that follows it, so
  480.  
  481.   (a(?i)b)c
  482.  
  483. matches abc and aBc and no other strings (assuming PCRE_CASELESS is not used).
  484. By this means, options can be made to have different settings in different
  485. parts of the pattern. Any changes made in one alternative do carry on
  486. into subsequent branches within the same subpattern. For example,
  487.  
  488.   (a(?i)b|c)
  489.  
  490. matches "ab", "aB", "c", and "C", even though when matching "C" the first
  491. branch is abandoned before the option setting. This is because the effects of
  492. option settings happen at compile time. There would be some very weird
  493. behaviour otherwise.
  494.  
  495. The PCRE-specific options PCRE_UNGREEDY and PCRE_EXTRA can be changed in the
  496. same way as the Perl-compatible options by using the characters U and X
  497. respectively. The (?X) flag setting is special in that it must always occur
  498. earlier in the pattern than any of the additional features it turns on, even
  499. when it is at top level. It is best put at the start.
  500.  
  501.  
  502. <a name="subs"></a><sh>SUBPATTERNS</sh>
  503. Subpatterns are delimited by parentheses (round brackets), which can be nested.
  504. Marking part of a pattern as a subpattern does two things:
  505.  
  506. 1. It localizes a set of alternatives. For example, the pattern
  507.  
  508.   cat(aract|erpillar|)
  509.  
  510. matches one of the words "cat", "cataract", or "caterpillar". Without the
  511. parentheses, it would match "cataract", "erpillar" or the empty string.
  512.  
  513. 2. It sets up the subpattern as a capturing subpattern (as defined above).
  514. When the whole pattern matches, that portion of the subject string that matched
  515. the subpattern is passed back to the caller via the <i>ovector</i> argument of
  516. <b>pcre_exec()</b>. Opening parentheses are counted from left to right (starting
  517. from 1) to obtain the numbers of the capturing subpatterns.
  518.  
  519. For example, if the string "the red king" is matched against the pattern
  520.  
  521.   the ((red|white) (king|queen))
  522.  
  523. the captured substrings are "red king", "red", and "king", and are numbered 1,
  524. 2, and 3.
  525.  
  526. The fact that plain parentheses fulfil two functions is not always helpful.
  527. There are often times when a grouping subpattern is required without a
  528. capturing requirement. If an opening parenthesis is followed by "?:", the
  529. subpattern does not do any capturing, and is not counted when computing the
  530. number of any subsequent capturing subpatterns. For example, if the string "the
  531. white queen" is matched against the pattern
  532.  
  533.   the ((?:red|white) (king|queen))
  534.  
  535. the captured substrings are "white queen" and "queen", and are numbered 1 and
  536. 2. The maximum number of captured substrings is 99, and the maximum number of
  537. all subpatterns, both capturing and non-capturing, is 200.
  538.  
  539. As a convenient shorthand, if any option settings are required at the start of
  540. a non-capturing subpattern, the option letters may appear between the "?" and
  541. the ":". Thus the two patterns
  542.  
  543.   (?i:saturday|sunday)
  544.   (?:(?i)saturday|sunday)
  545.  
  546. match exactly the same set of strings. Because alternative branches are tried
  547. from left to right, and options are not reset until the end of the subpattern
  548. is reached, an option setting in one branch does affect subsequent branches, so
  549. the above patterns match "SUNDAY" as well as "Saturday".
  550.  
  551.  
  552. <a name="repi"></a><sh>REPETITION</sh>
  553. Repetition is specified by quantifiers, which can follow any of the following
  554. items:
  555.  
  556.   a single character, possibly escaped
  557.   the . metacharacter
  558.   a character class
  559.   a back reference (see next section)
  560.   a parenthesized subpattern (unless it is an assertion - see below)
  561.  
  562. The general repetition quantifier specifies a minimum and maximum number of
  563. permitted matches, by giving the two numbers in curly brackets (braces),
  564. separated by a comma. The numbers must be less than 65536, and the first must
  565. be less than or equal to the second. For example:
  566.  
  567.   z{2,4}
  568.  
  569. matches "zz", "zzz", or "zzzz". A closing brace on its own is not a special
  570. character. If the second number is omitted, but the comma is present, there is
  571. no upper limit; if the second number and the comma are both omitted, the
  572. quantifier specifies an exact number of required matches. Thus
  573.  
  574.   [aeiou]{3,}
  575.  
  576. matches at least 3 successive vowels, but may match many more, while
  577.  
  578.   \d{8}
  579.  
  580. matches exactly 8 digits. An opening curly bracket that appears in a position
  581. where a quantifier is not allowed, or one that does not match the syntax of a
  582. quantifier, is taken as a literal character. For example, {,6} is not a
  583. quantifier, but a literal string of four characters.
  584.  
  585. The quantifier {0} is permitted, causing the expression to behave as if the
  586. previous item and the quantifier were not present.
  587.  
  588. For convenience (and historical compatibility) the three most common
  589. quantifiers have single-character abbreviations:
  590.  
  591. <pre>
  592.   *    is equivalent to {0,}
  593.   +    is equivalent to {1,}
  594.   ?    is equivalent to {0,1}
  595. </pre>
  596.  
  597. It is possible to construct infinite loops by following a subpattern that can
  598. match no characters with a quantifier that has no upper limit, for example:
  599.  
  600.   (a?)*
  601.  
  602. Earlier versions of Perl and PCRE used to give an error at compile time for
  603. such patterns. However, because there are cases where this can be useful, such
  604. patterns are now accepted, but if any repetition of the subpattern does in fact
  605. match no characters, the loop is forcibly broken.
  606.  
  607. By default, the quantifiers are "greedy", that is, they match as much as
  608. possible (up to the maximum number of permitted times), without causing the
  609. rest of the pattern to fail. The classic example of where this gives problems
  610. is in trying to match comments in C programs. These appear between the
  611. sequences /* and */ and within the sequence, individual * and / characters may
  612. appear. An attempt to match C comments by applying the pattern
  613.  
  614.   /\*.*\*/
  615.  
  616. to the string
  617.  
  618.   /* first command */  not comment  /* second comment */
  619.  
  620. fails, because it matches the entire string due to the greediness of the .*
  621. item.
  622.  
  623. However, if a quantifier is followed by a question mark, then it ceases to be
  624. greedy, and instead matches the minimum number of times possible, so the
  625. pattern
  626.  
  627.   /\*.*?\*/
  628.  
  629. does the right thing with the C comments. The meaning of the various
  630. quantifiers is not otherwise changed, just the preferred number of matches.
  631. Do not confuse this use of question mark with its use as a quantifier in its
  632. own right. Because it has two uses, it can sometimes appear doubled, as in
  633.  
  634.   \d??\d
  635.  
  636. which matches one digit by preference, but can match two if that is the only
  637. way the rest of the pattern matches.
  638.  
  639. If the PCRE_UNGREEDY option is set (an option which is not available in Perl)
  640. then the quantifiers are not greedy by default, but individual ones can be made
  641. greedy by following them with a question mark. In other words, it inverts the
  642. default behaviour.
  643.  
  644. When a parenthesized subpattern is quantified with a minimum repeat count that
  645. is greater than 1 or with a limited maximum, more store is required for the
  646. compiled pattern, in proportion to the size of the minimum or maximum.
  647.  
  648. If a pattern starts with .* then it is implicitly anchored, since whatever
  649. follows will be tried against every character position in the subject string.
  650. PCRE treats this as though it were preceded by \A.
  651.  
  652. When a capturing subpattern is repeated, the value captured is the substring
  653. that matched the final iteration. For example, after
  654.  
  655.   (tweedle[dume]{3}\s*)+
  656.  
  657. has matched "tweedledum tweedledee" the value of the captured substring is
  658. "tweedledee". However, if there are nested capturing subpatterns, the
  659. corresponding captured values may have been set in previous iterations. For
  660. example, after
  661.  
  662.   /(a|(b))+/
  663.  
  664. matches "aba" the value of the second captured substring is "b".
  665.  
  666.  
  667. <a name="bacr"></a><sh>BACK REFERENCES</sh>
  668. Outside a character class, a backslash followed by a digit greater than 0 (and
  669. possibly further digits) is a back reference to a capturing subpattern earlier
  670. (i.e. to its left) in the pattern, provided there have been that many previous
  671. capturing left parentheses.
  672.  
  673. However, if the decimal number following the backslash is less than 10, it is
  674. always taken as a back reference, and causes an error only if there are not
  675. that many capturing left parentheses in the entire pattern. In other words, the
  676. parentheses that are referenced need not be to the left of the reference for
  677. numbers less than 10. See the section entitled "Backslash" above for further
  678. details of the handling of digits following a backslash.
  679.  
  680. A back reference matches whatever actually matched the capturing subpattern in
  681. the current subject string, rather than anything matching the subpattern
  682. itself. So the pattern
  683.  
  684.   (sens|respons)e and \1ibility
  685.  
  686. matches "sense and sensibility" and "response and responsibility", but not
  687. "sense and responsibility". If caseful matching is in force at the time of the
  688. back reference, then the case of letters is relevant. For example,
  689.  
  690.   ((?i)rah)\s+\1
  691.  
  692. matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original
  693. capturing subpattern is matched caselessly.
  694.  
  695. There may be more than one back reference to the same subpattern. If a
  696. subpattern has not actually been used in a particular match, then any back
  697. references to it always fail. For example, the pattern
  698.  
  699.   (a|(bc))\2
  700.  
  701. always fails if it starts to match "a" rather than "bc". Because there may be
  702. up to 99 back references, all digits following the backslash are taken
  703. as part of a potential back reference number. If the pattern continues with a
  704. digit character, then some delimiter must be used to terminate the back
  705. reference. If the PCRE_EXTENDED option is set, this can be whitespace.
  706. Otherwise an empty comment can be used.
  707.  
  708. A back reference that occurs inside the parentheses to which it refers fails
  709. when the subpattern is first used, so, for example, (a\1) never matches.
  710. However, such references can be useful inside repeated subpatterns. For
  711. example, the pattern
  712.  
  713.   (a|b\1)+
  714.  
  715. matches any number of "a"s and also "aba", "ababaa" etc. At each iteration of
  716. the subpattern, the back reference matches the character string corresponding
  717. to the previous iteration. In order for this to work, the pattern must be such
  718. that the first iteration does not need to match the back reference. This can be
  719. done using alternation, as in the example above, or by a quantifier with a
  720. minimum of zero.
  721.  
  722.  
  723. <a name="asrt"></a><sh>ASSERTIONS</sh>
  724. An assertion is a test on the characters following or preceding the current
  725. matching point that does not actually consume any characters. The simple
  726. assertions coded as \b, \B, \A, \Z, \z, ^ and $ are described above. More
  727. complicated assertions are coded as subpatterns. There are two kinds: those
  728. that look ahead of the current position in the subject string, and those that
  729. look behind it.
  730.  
  731. An assertion subpattern is matched in the normal way, except that it does not
  732. cause the current matching position to be changed. Lookahead assertions start
  733. with (?= for positive assertions and (?! for negative assertions. For example,
  734.  
  735.   \w+(?=;)
  736.  
  737. matches a word followed by a semicolon, but does not include the semicolon in
  738. the match, and
  739.  
  740.   foo(?!bar)
  741.  
  742. matches any occurrence of "foo" that is not followed by "bar". Note that the
  743. apparently similar pattern
  744.  
  745.   (?!foo)bar
  746.  
  747. does not find an occurrence of "bar" that is preceded by something other than
  748. "foo"; it finds any occurrence of "bar" whatsoever, because the assertion
  749. (?!foo) is always true when the next three characters are "bar". A
  750. lookbehind assertion is needed to achieve this effect.
  751.  
  752. Lookbehind assertions start with (?<= for positive assertions and (?<! for
  753. negative assertions. For example,
  754.  
  755.   (?<!foo)bar
  756.  
  757. does find an occurrence of "bar" that is not preceded by "foo". The contents of
  758. a lookbehind assertion are restricted such that all the strings it matches must
  759. have a fixed length. However, if there are several alternatives, they do not
  760. all have to have the same fixed length. Thus
  761.  
  762.   (?<=bullock|donkey)
  763.  
  764. is permitted, but
  765.  
  766.   (?<!dogs?|cats?)
  767.  
  768. causes an error at compile time. Branches that match different length strings
  769. are permitted only at the top level of a lookbehind assertion. This is an
  770. extension compared with Perl 5.005, which requires all branches to match the
  771. same length of string. An assertion such as
  772.  
  773.   (?<=ab(c|de))
  774.  
  775. is not permitted, because its single top-level branch can match two different
  776. lengths, but it is acceptable if rewritten to use two top-level branches:
  777.  
  778.   (?<=abc|abde)
  779.  
  780. The implementation of lookbehind assertions is, for each alternative, to
  781. temporarily move the current position back by the fixed width and then try to
  782. match. If there are insufficient characters before the current position, the
  783. match is deemed to fail. Lookbehinds in conjunction with once-only subpatterns
  784. can be particularly useful for matching at the ends of strings; an example is
  785. given at the end of the section on once-only subpatterns.
  786.  
  787. Several assertions (of any sort) may occur in succession. For example,
  788.  
  789.   (?<=\d{3})(?<!999)foo
  790.  
  791. matches "foo" preceded by three digits that are not "999". Furthermore,
  792. assertions can be nested in any combination. For example,
  793.  
  794.   (?<=(?<!foo)bar)baz
  795.  
  796. matches an occurrence of "baz" that is preceded by "bar" which in turn is not
  797. preceded by "foo".
  798.  
  799. Assertion subpatterns are not capturing subpatterns, and may not be repeated,
  800. because it makes no sense to assert the same thing several times. If an
  801. assertion contains capturing subpatterns within it, these are always counted
  802. for the purposes of numbering the capturing subpatterns in the whole pattern.
  803. Substring capturing is carried out for positive assertions, but it does not
  804. make sense for negative assertions.
  805.  
  806. Assertions count towards the maximum of 200 parenthesized subpatterns.
  807.  
  808.  
  809. <a name="once"></a><sh>ONCE-ONLY SUBPATTERNS</sh>
  810. With both maximizing and minimizing repetition, failure of what follows
  811. normally causes the repeated item to be re-evaluated to see if a different
  812. number of repeats allows the rest of the pattern to match. Sometimes it is
  813. useful to prevent this, either to change the nature of the match, or to cause
  814. it fail earlier than it otherwise might, when the author of the pattern knows
  815. there is no point in carrying on.
  816.  
  817. Consider, for example, the pattern \d+foo when applied to the subject line
  818.  
  819.   123456bar
  820.  
  821. After matching all 6 digits and then failing to match "foo", the normal
  822. action of the matcher is to try again with only 5 digits matching the \d+
  823. item, and then with 4, and so on, before ultimately failing. Once-only
  824. subpatterns provide the means for specifying that once a portion of the pattern
  825. has matched, it is not to be re-evaluated in this way, so the matcher would
  826. give up immediately on failing to match "foo" the first time. The notation is
  827. another kind of special parenthesis, starting with (?> as in this example:
  828.  
  829.   (?>\d+)bar
  830.  
  831. This kind of parenthesis "locks up" the  part of the pattern it contains once
  832. it has matched, and a failure further into the pattern is prevented from
  833. backtracking into it. Backtracking past it to previous items, however, works as
  834. normal.
  835.  
  836. An alternative description is that a subpattern of this type matches the string
  837. of characters that an identical standalone pattern would match, if anchored at
  838. the current point in the subject string.
  839.  
  840. Once-only subpatterns are not capturing subpatterns. Simple cases such as the
  841. above example can be though of as a maximizing repeat that must swallow
  842. everything it can. So, while both \d+ and \d+? are prepared to adjust the
  843. number of digits they match in order to make the rest of the pattern match,
  844. (?>\d+) can only match an entire sequence of digits.
  845.  
  846. This construction can of course contain arbitrarily complicated subpatterns,
  847. and it can be nested.
  848.  
  849. Once-only subpatterns can be used in conjunction with lookbehind assertions to
  850. specify efficient matching at the end of the subject string. Consider a simple
  851. pattern such as
  852.  
  853.   abcd$
  854.  
  855. when applied to a long string which does not match it. Because matching
  856. proceeds from left to right, PCRE will look for each "a" in the subject and
  857. then see if what follows matches the rest of the pattern. If the pattern is
  858. specified as
  859.  
  860.   .*abcd$
  861.  
  862. then the initial .* matches the entire string at first, but when this fails, it
  863. backtracks to match all but the last character, then all but the last two
  864. characters, and so on. Once again the search for "a" covers the entire string,
  865. from right to left, so we are no better off. However, if the pattern is written
  866. as
  867.  
  868.   (?>.*)(?<=abcd)
  869.  
  870. then there can be no backtracking for the .* item; it can match only the entire
  871. string. The subsequent lookbehind assertion does a single test on the last four
  872. characters. If it fails, the match fails immediately. For long strings, this
  873. approach makes a significant difference to the processing time.
  874.  
  875.  
  876. <a name="cond"></a><sh>CONDITIONAL SUBPATTERNS</sh>
  877. It is possible to cause the matching process to obey a subpattern
  878. conditionally or to choose between two alternative subpatterns, depending on
  879. the result of an assertion, or whether a previous capturing subpattern matched
  880. or not. The two possible forms of conditional subpattern are
  881.  
  882.   (?(condition)yes-pattern)
  883.   (?(condition)yes-pattern|no-pattern)
  884.  
  885. If the condition is satisfied, the yes-pattern is used; otherwise the
  886. no-pattern (if present) is used. If there are more than two alternatives in the
  887. subpattern, a compile-time error occurs.
  888.  
  889. There are two kinds of condition. If the text between the parentheses consists
  890. of a sequence of digits, then the condition is satisfied if the capturing
  891. subpattern of that number has previously matched. Consider the following
  892. pattern, which contains non-significant white space to make it more readable
  893. (assume the PCRE_EXTENDED option) and to divide it into three parts for ease
  894. of discussion:
  895.  
  896.   ( \( )?    [^()]+    (?(1) \) )
  897.  
  898. The first part matches an optional opening parenthesis, and if that
  899. character is present, sets it as the first captured substring. The second part
  900. matches one or more characters that are not parentheses. The third part is a
  901. conditional subpattern that tests whether the first set of parentheses matched
  902. or not. If they did, that is, if subject started with an opening parenthesis,
  903. the condition is true, and so the yes-pattern is executed and a closing
  904. parenthesis is required. Otherwise, since no-pattern is not present, the
  905. subpattern matches nothing. In other words, this pattern matches a sequence of
  906. non-parentheses, optionally enclosed in parentheses.
  907.  
  908. If the condition is not a sequence of digits, it must be an assertion. This may
  909. be a positive or negative lookahead or lookbehind assertion. Consider this
  910. pattern, again containing non-significant white space, and with the two
  911. alternatives on the second line:
  912.  
  913.   (?(?=[^a-z]*[a-z])
  914.   \d{2}[a-z]{3}-\d{2}  |  \d{2}-\d{2}-\d{2} )
  915.  
  916. The condition is a positive lookahead assertion that matches an optional
  917. sequence of non-letters followed by a letter. In other words, it tests for the
  918. presence of at least one letter in the subject. If a letter is found, the
  919. subject is matched against the first alternative; otherwise it is matched
  920. against the second. This pattern matches strings in one of the two forms
  921. dd-aaa-dd or dd-dd-dd, where aaa are letters and dd are digits.
  922.  
  923.  
  924. <a name="comm"></a><sh>COMMENTS</sh>
  925. The sequence (?# marks the start of a comment which continues up to the next
  926. closing parenthesis. Nested parentheses are not permitted. The characters
  927. that make up a comment play no part in the pattern matching at all.
  928.  
  929. If the PCRE_EXTENDED option is set, an unescaped # character outside a
  930. character class introduces a comment that continues up to the next newline
  931. character in the pattern.
  932.  
  933.  
  934. <a name="perf"></a><sh>PERFORMANCE</sh>
  935. Certain items that may appear in patterns are more efficient than others. It is
  936. more efficient to use a character class like [aeiou] than a set of alternatives
  937. such as (a|e|i|o|u). In general, the simplest construction that provides the
  938. required behaviour is usually the most efficient. Jeffrey Friedl's book
  939. contains a lot of discussion about optimizing regular expressions for efficient
  940. performance.
  941.  
  942.