home *** CD-ROM | disk | FTP | other *** search
/ RISC DISC 2 / RISC_DISC_2.iso / pd_share / utilities / cli / gnuinfo / etc / info / REGEX < prev   
Encoding:
Text File  |  1994-09-13  |  22.7 KB  |  569 lines

  1. Info file: regex,    -*-Text-*-
  2. produced by texinfo-format-buffer
  3. from file: regex.texi
  4.  
  5.  
  6.  
  7.  
  8. 
  9. File: regex  Node: top, Up: (dir), Next: syntax
  10.  
  11. "regex" regular expression matching library.
  12. ********************************************
  13.  
  14.  
  15. Overview
  16. ========
  17.  
  18. Regular expression matching allows you to test whether a string fits
  19. into a specific syntactic shape.  You can also search a string for a
  20. substring that fits a pattern.
  21.  
  22. A regular expression describes a set of strings.  The simplest case is
  23. one that describes a particular string; for example, the string `foo'
  24. when regarded as a regular expression matches `foo' and nothing else.
  25. Nontrivial regular expressions use certain special constructs so that
  26. they can match more than one string.  For example, the regular expression
  27. `foo\|bar' matches either the string `foo' or the string `bar'; the
  28. regular expression `c[ad]*r' matches any of the strings `cr', `car',
  29. `cdr', `caar', `cadddar' and all other such strings with any number of
  30. `a''s and `d''s.
  31.  
  32. The first step in matching a regular expression is to compile it.
  33. You must supply the pattern string and also a pattern buffer to hold
  34. the compiled result.  That result contains the pattern in an internal
  35. format that is easier to use in matching.
  36.  
  37. Having compiled a pattern, you can match it against strings.  You can
  38. match the compiled pattern any number of times against different
  39. strings.
  40.  
  41. * Menu:
  42.  
  43. * syntax::    Syntax of regular expressions
  44. * directives::    Meaning of characters as regex string directives.
  45. * emacs::    Additional character directives available
  46.           only for use within Emacs.
  47. * programming:: Using the regex library from C programs
  48. * unix::    Unix-compatible entry-points to regex library
  49.  
  50. 
  51. File: regex  Node: syntax, Prev: top, Up: top, Next: directives
  52.  
  53. Syntax of Regular Expressions
  54. =============================
  55.  
  56. Regular expressions have a syntax in which a few characters are special
  57. constructs and the rest are "ordinary".  An ordinary character is a
  58. simple regular expression which matches that character and nothing else.
  59. The special characters are `$', `^', `.', `*', `+', `?', `[', `]' and
  60. `\'.  Any other character appearing in a regular expression is ordinary,
  61. unless a `\' precedes it.
  62.  
  63. For example, `f' is not a special character, so it is ordinary,
  64. and therefore `f' is a regular expression that matches the string `f'
  65. and no other string.  (It does *not* match the string `ff'.)  Likewise,
  66. `o' is a regular expression that matches only `o'.
  67.  
  68. Any two regular expressions A and B can be concatenated.
  69. The result is a regular expression which matches a string if A
  70. matches some amount of the beginning of that string and B
  71. matches the rest of the string.
  72.  
  73. As a simple example, we can concatenate the regular expressions
  74. `f' and `o' to get the regular expression `fo',
  75. which matches only the string `fo'.  Still trivial.
  76.  
  77. Note: for Unix compatibility, special characters are treated as
  78. ordinary ones if they are in contexts where their special meanings
  79. make no sense.  For example, `*foo' treats `*' as ordinary since
  80. there is no preceding expression on which the `*' can act.
  81. It is poor practice to depend on this behavior; better to quote
  82. the special character anyway, regardless of where is appears.
  83.  
  84.  
  85. 
  86. File: regex  Node: directives, Prev: syntax, Up: top, Next: emacs
  87.  
  88. The following are the characters and character sequences which have
  89. special meaning within regular expressions.
  90. Any character not mentioned here is not special; it stands for exactly
  91. itself for the purposes of searching and matching.  *Note syntax::.
  92.  
  93. `.'
  94.      is a special character that matches anything except a newline.
  95.      Using concatenation, we can make regular expressions like `a.b'
  96.      which matches any three-character string which begins with `a' and
  97.      ends with `b'.
  98.  
  99. `*'
  100.      is not a construct by itself; it is a suffix, which means the
  101.      preceding regular expression is to be repeated as many times as
  102.      possible.  In `fo*', the `*' applies to the `o', so `fo*' matches
  103.      `f' followed by any number of `o''s.
  104.  
  105.      The case of zero `o''s is allowed: `fo*' does match `f'.
  106.  
  107.      `*' always applies to the *smallest* possible preceding expression.
  108.      Thus, `fo*' has a repeating `o', not a repeating `fo'.
  109.  
  110.      The matcher processes a `*' construct by matching, immediately, as
  111.      many repetitions as can be found.  Then it continues with the rest
  112.      of the pattern.  If that fails, backtracking occurs, discarding
  113.      some of the matches of the `*''d construct in case that makes it
  114.      possible to match the rest of the pattern.  For example, matching
  115.      `c[ad]*ar' against the string `caddaar', the `[ad]*' first matches
  116.      `addaa', but this does not allow the next `a' in the pattern to
  117.      match.  So the last of the matches of `[ad]' is undone and the
  118.      following `a' is tried again.  Now it succeeds.
  119.  
  120. `+'
  121.      `+' is like `*' except that at least one match for the preceding
  122.      pattern is required for `+'.  Thus, `c[ad]+r' does not match
  123.      `cr' but does match anything else that `c[ad]*r' would match.
  124.  
  125. `?'
  126.      `?' is like `*' except that it allows either zero or one match
  127.      for the preceding pattern.  Thus, `c[ad]?r' matches `cr' or
  128.      `car' or `cdr', and nothing else.
  129.  
  130. `[ ... ]'
  131.      `[' begins a "character set", which is terminated by a `]'.  In the
  132.      simplest case, the characters between the two form the set.  Thus,
  133.      `[ad]' matches either `a' or `d', and `[ad]*' matches any string of
  134.      `a''s and `d''s (including the empty string), from which it follows
  135.      that `c[ad]*r' matches `car', etc.
  136.  
  137.      Character ranges can also be included in a character set, by
  138.      writing two characters with a `-' between them.  Thus, `[a-z]'
  139.      matches any lower-case letter.  Ranges may be intermixed freely
  140.      with individual characters, as in `[a-z$%.]', which matches any
  141.      lower case letter or `$', `%' or period.
  142.  
  143.      Note that the usual special characters are not special any more
  144.      inside a character set.  A completely different set of special
  145.      characters exists inside character sets: `]', `-' and `^'.
  146.  
  147.      To include a `]' in a character set, you must make it the first
  148.      character.  For example, `[]a]' matches `]' or `a'.  To include a
  149.      `-', you must use it in a context where it cannot possibly indicate
  150.      a range: that is, as the first character, or immediately after a
  151.      range.
  152.  
  153. `[^ ... ]'
  154.      `[^' begins a "complement character set", which matches any
  155.      character except the ones specified.  Thus, `[^a-z0-9A-Z]' matches
  156.      all characters *except* letters and digits.
  157.  
  158.      `^' is not special in a character set unless it is the first
  159.      character.  The character following the `^' is treated as if it
  160.      were first (it may be a `-' or a `]').
  161.  
  162. `^'
  163.      is a special character that matches the empty string -- but only if
  164.      at the beginning of a line in the text being matched.  Otherwise it
  165.      fails to match anything.  Thus, `^foo' matches a `foo' which occurs
  166.      at the beginning of a line.
  167.  
  168. `$'
  169.      is similar to `^' but matches only at the end of a line.  Thus,
  170.      `xx*$' matches a string of one or more `x''s at the end of a line.
  171.  
  172. `\'
  173.      has two functions: it quotes the above special characters
  174.      (including `\'), and it introduces additional special constructs.
  175.  
  176.      Because `\' quotes special characters, `\$' is a regular expression
  177.      which matches only `$', and `\[' is a regular expression which
  178.      matches only `[', and so on.
  179.  
  180.      For the most part, `\' followed by any character matches only that
  181.      character.  However, there are several exceptions: characters
  182.      which, when preceded by `\', are special constructs.  Such
  183.      characters are always ordinary when encountered on their own.
  184.  
  185.      No new special characters will ever be defined.  All extensions to
  186.      the regular expression syntax are made by defining new
  187.      two-character constructs that begin with `\'.
  188.  
  189. `\|'
  190.      specifies an alternative.  Two regular expressions A and B with
  191.      `\|' in between form an expression that matches anything that
  192.      either A or B will match.
  193.  
  194.      Thus, `foo\|bar' matches either `foo' or `bar' but no other string.
  195.  
  196.      `\|' applies to the largest possible surrounding expressions.  Only
  197.      a surrounding `\( ... \)' grouping can limit the grouping power of
  198.      `\|'.
  199.  
  200.      Full backtracking capability exists when multiple `\|''s are used.
  201.  
  202. `\( ... \)'
  203.      is a grouping construct that serves three purposes:
  204.  
  205.        1. To enclose a set of `\|' alternatives for other operations.
  206.           Thus, `\(foo\|bar\)x' matches either `foox' or `barx'.
  207.  
  208.        2. To enclose a complicated expression for the postfix `*' to
  209.           operate on.  Thus, `ba\(na\)*' matches `bananana', etc., with
  210.           any (zero or more) number of `na''s.
  211.  
  212.        3. To mark a matched substring for future reference.
  213.  
  214.  
  215.      This last application is not a consequence of the idea of a
  216.      parenthetical grouping; it is a separate feature which happens to
  217.      be assigned as a second meaning to the same `\( ... \)' construct
  218.      because there is no conflict in practice between the two meanings.
  219.      Here is an explanation of this feature:
  220.  
  221. `\DIGIT'
  222.      After the end of a `\( ... \)' construct, the matcher remembers the
  223.      beginning and end of the text matched by that construct.  Then,
  224.      later on in the regular expression, you can use `\' followed by
  225.      DIGIT to mean "match the same text matched the DIGIT'th time by the
  226.      `\( ... \)' construct."  The `\( ... \)' constructs are numbered in
  227.      order of commencement in the regexp.
  228.  
  229.      The strings matching the first nine `\( ... \)' constructs
  230.      appearing in a regular expression are assigned numbers 1 through 9
  231.      in order of their beginnings.  `\1' through `\9' may be used to
  232.      refer to the text matched by the corresponding `\( ... \)'
  233.      construct.
  234.  
  235.      For example, `\(.*\)\1' matches any string that is composed of two
  236.      identical halves.  The `\(.*\)' matches the first half, which may
  237.      be anything, but the `\1' that follows must match the same exact
  238.      text.
  239.  
  240. `\b'
  241.      matches the empty string, but only if it is at the beginning or end
  242.      of a word.  Thus, `\bfoo\b' matches any occurrence of `foo' as a
  243.      separate word.  `\bball\(s\|\)\b' matches `ball' or `balls' as a
  244.      separate word.
  245.  
  246. `\B'
  247.      matches the empty string, provided it is *not* at the beginning or
  248.      end of a word.
  249.  
  250. `\<'
  251.      matches the empty string, but only if it is at the beginning
  252.      of a word.
  253.  
  254. `\>'
  255.      matches the empty string, but only if it is at the end of a word.
  256.  
  257. `\w'
  258.      matches any word-constituent character.
  259.  
  260. `\W'
  261.      matches any character that is not a word-constituent.
  262.  
  263. There are a number of additional `\' regexp directives available for use
  264. within Emacs only.
  265. (*Note emacs::).
  266.  
  267. 
  268. File: regex  Node: emacs, Prev: directives, Up: top, Next: programming
  269.  
  270. Constructs Available in Emacs Only
  271. ----------------------------------
  272.  
  273. `\`'
  274.      matches the empty string, but only if it is at the beginning of the
  275.      buffer.
  276.  
  277. `\''
  278.      matches the empty string, but only if it is at the end of the
  279.      buffer.
  280.  
  281. `\sCODE'
  282.      matches any character whose syntax is CODE.  CODE is a letter which
  283.      represents a syntax code: thus, `w' for word constituent, `-' for
  284.      whitespace, `(' for open-parenthesis, etc.  See the documentation
  285.      for the Emacs function `modify-syntax-entry' for further details.
  286.  
  287.      Thus, `\s(' matches any character with open-parenthesis syntax.
  288.  
  289. `\SCODE'
  290.      matches any character whose syntax is not CODE.
  291.  
  292. 
  293. File: regex  Node: programming, Prev: emacs, Up: top, Next: compiling
  294.  
  295. Programming using the `regex' library
  296. =====================================
  297.  
  298. The subnodes accessible from this menu give information on entry
  299. points and data structures which C programs need to interface to the
  300. `regex' library.
  301.  
  302. * Menu:
  303.  
  304. * compiling::    How to compile regular expressions
  305. * matching::    Matching compiled regular expressions
  306. * searching::    Searching for compiled regular expressions
  307. * translation::    Translating characters into other characters
  308.           (for both compilation and matching)
  309. * registers::    determining what was matched
  310. * split::    matching data which is split into two pieces
  311. * unix::    Unix-compatible entry-points to regex library
  312.  
  313. 
  314. File: regex  Node: compiling, Prev: programming, Up: programming, Next: matching
  315.  
  316. Compiling a Regular Expression
  317. ------------------------------
  318.  
  319. To compile a regular expression, you must supply a pattern buffer.
  320. This is a structure defined, in the include file `regex.h', as follows:
  321.     
  322.      struct re_pattern_buffer
  323.        {
  324.          char *buffer   /* Space holding the compiled pattern commands. */
  325.          int allocated  /* Size of space that  buffer  points to */
  326.          int used       /* Length of portion of buffer actually occupied */
  327.          char *fastmap; /* Pointer to fastmap, if any, or zero if none. */
  328.                         /* re_search uses the fastmap, if there is one,
  329.                            to skip quickly over totally implausible
  330.                            characters */
  331.          char *translate;
  332.                         /* Translate table to apply to characters before
  333.                            comparing, or zero for no translation.
  334.                            The translation is applied to a pattern when
  335.                            it is compiled and to data when it is matched. */
  336.          char fastmap_accurate;
  337.                         /* Set to zero when a new pattern is stored,
  338.                            set to one when the fastmap is updated from it. */
  339.        };
  340.  
  341. Before compiling a pattern, you must initialize the `buffer' field to
  342. point to a block of memory obtained with `malloc',
  343. and the `allocated' field to the size of that block, in bytes.
  344. The pattern compiler will replace this block with a larger one if necessary.
  345.  
  346. You must also initialize the `translate' field to point to the translate
  347. table that you will use when you match the compiled pattern, or to zero
  348. if you will use no translate table when you match.  *Note translation::.
  349.  
  350. Then call `re_compile_pattern' to compile a regular expression
  351. into the buffer:
  352.      re_compile_pattern (REGEX, REGEX_SIZE, BUF)
  353.  
  354. REGEX is the address of the regular expression (`char *'),
  355. REGEX_SIZE is its length (`int'),
  356. BUF is the address of the buffer (`struct re_pattern_buffer *').
  357.  
  358. `re_compile_pattern' returns zero if it succeeds in compiling the regular
  359. expression.  In that case, `*buf' now contains the results.
  360. Otherwise, `re_compile_pattern' returns a string which serves as
  361. an error message.
  362.  
  363. After compiling, if you wish to search for the pattern, you must
  364. initialize the `fastmap' component of the pattern buffer.
  365. *Note searching::.
  366.  
  367. 
  368. File: regex  Node: matching, Prev: compiling, Up: programming, Next: searching
  369.  
  370. Matching a Compiled Pattern
  371. ---------------------------
  372.  
  373. Once a regular expression has been compiled into a pattern buffer,
  374. you can match the pattern buffer against a string with `re_match'.
  375.  
  376.      re_match (BUF, STRING, SIZE, POS, REGS)
  377.  
  378. BUF is, once again, the address of the buffer (`struct re_pattern_buffer *').
  379. STRING is the string to be matched (`char *').
  380. SIZE is the length of that string (`int').
  381. POS is the position within the string at which to begin matching (`int').
  382. The beginning of the string is position 0.
  383. REGS is described below.  Normally it is zero.  *Note registers::.
  384.  
  385. `re_match' returns `-1' if the pattern does not match; otherwise,
  386. it returns the length of the portion of `string' which was matched.
  387.  
  388. For example, suppose that BUF points to a buffer containing the result
  389. of compiling `x*', STRING points to `xxxxxy', and SIZE is `6'.
  390. Suppose that POS is `2'.  Then the last three `x''s will be matched,
  391. so `re_match' will return `3'.
  392. If POS is zero, the value will be `5'.
  393. If POS is `5' or `6', the value will be zero, meaning that the null string
  394. was successfully matched.
  395. Note that since `x*' matches the empty string, it will never entirely fail.
  396.  
  397. It is up to the caller to avoid passing a value of POS that results in
  398. matching outside the specified string.  POS must not be negative and
  399. must not be greater than SIZE.
  400.  
  401. 
  402. File: regex  Node: searching, Prev: matching, Up: programming, Next: translation
  403.  
  404. Searching for a Match
  405. ---------------------
  406.  
  407. Searching means trying successive starting positions for a match until a
  408. match is found.  To search, you supply a compiled pattern buffer.  Before
  409. searching you must initialize the `fastmap' field of the pattern
  410. buffer (see below).
  411.  
  412.      re_search (BUF, STRING, SIZE, STARTPOS, RANGE, REGS)
  413.  
  414. is called like `re_match' except that the POS argument is replaced by
  415. two arguments STARTPOS and RANGE.  `re_search' tests for a match
  416. starting at index STARTPOS, then at `STARTPOS + 1', and so on.  It tries
  417. RANGE consecutive positions before giving up and returning `-1'.  If a
  418. match is found, `re_search' returns the index at which the match was
  419. found.
  420.  
  421. If RANGE is negative, RE_SEARCH tries starting positions STARTPOS,
  422. `STARTPOS - 1', ... in that order.  `|RANGE|' is the number of tries
  423. made.
  424.  
  425. It is up to the caller to avoid passing value of STARTPOS and RANGE that
  426. result in matching outside the specified string.  STARTPOS must be
  427. between zero and SIZE, inclusive, and so must `STARTPOS + RANGE - 1' (if
  428. RANGE is positive) or `STARTPOS + RANGE + 1' (if RANGE is negative).
  429.  
  430. If you may be searching over a long distance (that is, trying many
  431. different match starting points) with a compiled pattern, you should use a
  432. "fastmap" in it.  This is a block of 256 bytes, whose address is
  433. placed in the `fastmap' component of the pattern buffer.  The first
  434. time you search for a particular compiled pattern, the fastmap is set so
  435. that `FASTMAP[CH]' is nonzero if the character CH
  436. might possibly start a match for this pattern.  `re_search' checks
  437. each character against the fastmap so that it can skip more quickly over
  438. non-matches.
  439.  
  440. If you do not want a fastmap, store zero in the `fastmap' component of the
  441. pattern buffer before calling `re_search'.
  442.  
  443. In either case, you must initialize this component in a pattern buffer
  444. before you can use that buffer in a search; but you can choose as an
  445. initial value either zero or the address of a suitable block of memory.
  446.  
  447. If you compile a new pattern in an existing pattern buffer, it is not
  448. necessary to reinitialize the `fastmap' component (unless you
  449. wish to override your previous choice).
  450.  
  451. 
  452. File: regex  Node: translation, Prev: searching, Up: programming, Next: registers
  453.  
  454. Translate Tables
  455. ----------------
  456.  
  457. With a translate table, you can apply a transformation to all characters
  458. before they are compared.  For example, a table that maps lower case letters
  459. into upper case (or vice versa) causes differences in case to be ignored
  460. by matching.
  461.  
  462. A translate table is a block of 256 bytes.  Each character of raw data is
  463. used as an index in the translate table.  The value found there is used
  464. instead of the original character.  Each character in a regular
  465. expression, except for the syntactic constructs, is translated when the
  466. expression is compiled.  Each character of a string being matched is
  467. translated whenever it is compared or tested.
  468.  
  469. A suitable translate table to ignore differences in case maps all
  470. characters into themselves, except for lower case letters, which are
  471. mapped into the corresponding upper case letters.
  472. It could be initialized by:
  473.  
  474.      for (i = 0; i < 0400; i++)
  475.        table[i] = i;
  476.      for (i = 'a'; i <= 'z'; i++)
  477.        table[i] = i - 040;
  478.  
  479. You specify the use of a translate table by putting its address in the
  480. TRANSLATE component of the compiled pattern buffer.  If this component
  481. is zero, no translation is done.  Since both compilation and matching use
  482. the translate table, you must use the same table contents for both
  483. operations or confusing things will happen.
  484.  
  485. 
  486. File: regex  Node: registers, Prev: translation, Up: programming, Next: split
  487.  
  488. Registers: or "What Did the `\( ... \)' Groupings Actually Match?"
  489. ------------------------------------------------------------------
  490.  
  491. If you want to find out, after the match, what each of the first nine
  492. `\( ... \)' groupings actually matched, you can pass the REGS argument
  493. to the match or search function.  Pass the address of a structure of this type:
  494.  
  495.      struct re_registers
  496.        {
  497.          int start[RE_NREGS];
  498.          int end[RE_NREGS];
  499.        };
  500.  
  501.   `re_match' and `re_search' will store into this structure the data you
  502. want.  `REGS->start[REG]' will be the index in STRING of the beginning
  503. of the data matched by the REG'th `\( ... \)' grouping, and
  504. `REGS->end[REG]' will be the index of the end of that data (the index of
  505. the first character beyond those matched).  The values in the start and
  506. end arrays at indexes greater than the number of `\( ... \)' groupings
  507. present in the regular expression will be set to the value -1.  Register
  508. numbers start at 1 and run to `RE_NREGS - 1' (normally `9').
  509. `REGS->start[0]' and `REGS->end[0]' are similar but describe the extent
  510. of the substring matched by the entire pattern.
  511.  
  512.   Both `struct re_registers' and `RE_NREGS' are defined in `regex.h'.
  513.  
  514. 
  515. File: regex  Node: split, Prev: registers, Up: programming, Next: unix
  516.  
  517. Matching against Split Data
  518. ---------------------------
  519.  
  520. The functions `re_match_2' and `re_search_2' allow one to match in or search
  521. data which is divided into two strings.
  522.  
  523. `re_match_2' works like `re_match' except that two data strings and
  524. sizes must be given.
  525.  
  526.      re_match_2 (BUF, STRING1, SIZE1, STRING2, SIZE2, POS, REGS)
  527.  
  528. The matcher regards the contents of STRING1 as effectively followed by
  529. the contents of STRING2, and matches the combined string against the
  530. pattern in BUF.
  531.  
  532. `re_search_2' is likewise similar to `re_search':
  533.  
  534.      re_search_2 (BUF, STRING1, SIZE1, STRING2, SIZE2, STARTPOS, RANGE, REGS)
  535.  
  536. The value returned by RE_SEARCH_2 is an index into the combined data
  537. made up of STRING1 and STRING2.  It never exceeds `SIZE1 + SIZE2'.
  538. The values returned in the REGS structure (if there is one) are likewise
  539. indices in the combined data.
  540.  
  541. 
  542. File: regex  Node: unix, Prev: split, Up: programming
  543.  
  544. Unix-Compatible Entry Points
  545. ----------------------------
  546.  
  547. The standard Berkeley Unix way to compile a regular expression is to call
  548. `re_comp'.  This function takes a single argument, the address of the
  549. regular expression, which is assumed to be terminated by a null character.
  550.  
  551. `re_comp' does not ask you to specify a pattern buffer because it has its
  552. own pattern buffer --- just one.  Using `re_comp', one may match only the
  553. most recently compiled regular expression.
  554.  
  555. The value of `re_comp' is zero for success or else an error message string,
  556. as for `re_compile_pattern'.
  557.  
  558. Calling `re_comp' with the null string as argument it has no effect;
  559. the contents of the buffer remain unchanged.
  560.  
  561. The standard Berkeley Unix way to match the last regular expression compiled
  562. is to call `re_exec'.  This takes a single argument, the address of
  563. the string to be matched.  This string is assumed to be terminated by
  564. a null character.  Matching is tried starting at each position in the
  565. string.  `re_exec' returns `1' for success or `0' for failure.
  566. One cannot find out how long a substring was matched, nor what the
  567. `\( ... \)' groupings matched.
  568.  
  569.