api-regex.texi 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. @c -*-texinfo-*-
  2. @c This is part of the GNU Guile Reference Manual.
  3. @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007, 2009, 2010
  4. @c Free Software Foundation, Inc.
  5. @c See the file guile.texi for copying conditions.
  6. @node Regular Expressions
  7. @section Regular Expressions
  8. @tpindex Regular expressions
  9. @cindex regular expressions
  10. @cindex regex
  11. @cindex emacs regexp
  12. A @dfn{regular expression} (or @dfn{regexp}) is a pattern that
  13. describes a whole class of strings. A full description of regular
  14. expressions and their syntax is beyond the scope of this manual;
  15. an introduction can be found in the Emacs manual (@pxref{Regexps,
  16. , Syntax of Regular Expressions, emacs, The GNU Emacs Manual}), or
  17. in many general Unix reference books.
  18. If your system does not include a POSIX regular expression library,
  19. and you have not linked Guile with a third-party regexp library such
  20. as Rx, these functions will not be available. You can tell whether
  21. your Guile installation includes regular expression support by
  22. checking whether @code{(provided? 'regex)} returns true.
  23. The following regexp and string matching features are provided by the
  24. @code{(ice-9 regex)} module. Before using the described functions,
  25. you should load this module by executing @code{(use-modules (ice-9
  26. regex))}.
  27. @menu
  28. * Regexp Functions:: Functions that create and match regexps.
  29. * Match Structures:: Finding what was matched by a regexp.
  30. * Backslash Escapes:: Removing the special meaning of regexp
  31. meta-characters.
  32. @end menu
  33. @node Regexp Functions
  34. @subsection Regexp Functions
  35. By default, Guile supports POSIX extended regular expressions.
  36. That means that the characters @samp{(}, @samp{)}, @samp{+} and
  37. @samp{?} are special, and must be escaped if you wish to match the
  38. literal characters.
  39. This regular expression interface was modeled after that
  40. implemented by SCSH, the Scheme Shell. It is intended to be
  41. upwardly compatible with SCSH regular expressions.
  42. Zero bytes (@code{#\nul}) cannot be used in regex patterns or input
  43. strings, since the underlying C functions treat that as the end of
  44. string. If there's a zero byte an error is thrown.
  45. Patterns and input strings are treated as being in the locale
  46. character set if @code{setlocale} has been called (@pxref{Locales}),
  47. and in a multibyte locale this includes treating multi-byte sequences
  48. as a single character. (Guile strings are currently merely bytes,
  49. though this may change in the future, @xref{Conversion to/from C}.)
  50. @deffn {Scheme Procedure} string-match pattern str [start]
  51. Compile the string @var{pattern} into a regular expression and compare
  52. it with @var{str}. The optional numeric argument @var{start} specifies
  53. the position of @var{str} at which to begin matching.
  54. @code{string-match} returns a @dfn{match structure} which
  55. describes what, if anything, was matched by the regular
  56. expression. @xref{Match Structures}. If @var{str} does not match
  57. @var{pattern} at all, @code{string-match} returns @code{#f}.
  58. @end deffn
  59. Two examples of a match follow. In the first example, the pattern
  60. matches the four digits in the match string. In the second, the pattern
  61. matches nothing.
  62. @example
  63. (string-match "[0-9][0-9][0-9][0-9]" "blah2002")
  64. @result{} #("blah2002" (4 . 8))
  65. (string-match "[A-Za-z]" "123456")
  66. @result{} #f
  67. @end example
  68. Each time @code{string-match} is called, it must compile its
  69. @var{pattern} argument into a regular expression structure. This
  70. operation is expensive, which makes @code{string-match} inefficient if
  71. the same regular expression is used several times (for example, in a
  72. loop). For better performance, you can compile a regular expression in
  73. advance and then match strings against the compiled regexp.
  74. @deffn {Scheme Procedure} make-regexp pat flag@dots{}
  75. @deffnx {C Function} scm_make_regexp (pat, flaglst)
  76. Compile the regular expression described by @var{pat}, and
  77. return the compiled regexp structure. If @var{pat} does not
  78. describe a legal regular expression, @code{make-regexp} throws
  79. a @code{regular-expression-syntax} error.
  80. The @var{flag} arguments change the behavior of the compiled
  81. regular expression. The following values may be supplied:
  82. @defvar regexp/icase
  83. Consider uppercase and lowercase letters to be the same when
  84. matching.
  85. @end defvar
  86. @defvar regexp/newline
  87. If a newline appears in the target string, then permit the
  88. @samp{^} and @samp{$} operators to match immediately after or
  89. immediately before the newline, respectively. Also, the
  90. @samp{.} and @samp{[^...]} operators will never match a newline
  91. character. The intent of this flag is to treat the target
  92. string as a buffer containing many lines of text, and the
  93. regular expression as a pattern that may match a single one of
  94. those lines.
  95. @end defvar
  96. @defvar regexp/basic
  97. Compile a basic (``obsolete'') regexp instead of the extended
  98. (``modern'') regexps that are the default. Basic regexps do
  99. not consider @samp{|}, @samp{+} or @samp{?} to be special
  100. characters, and require the @samp{@{...@}} and @samp{(...)}
  101. metacharacters to be backslash-escaped (@pxref{Backslash
  102. Escapes}). There are several other differences between basic
  103. and extended regular expressions, but these are the most
  104. significant.
  105. @end defvar
  106. @defvar regexp/extended
  107. Compile an extended regular expression rather than a basic
  108. regexp. This is the default behavior; this flag will not
  109. usually be needed. If a call to @code{make-regexp} includes
  110. both @code{regexp/basic} and @code{regexp/extended} flags, the
  111. one which comes last will override the earlier one.
  112. @end defvar
  113. @end deffn
  114. @deffn {Scheme Procedure} regexp-exec rx str [start [flags]]
  115. @deffnx {C Function} scm_regexp_exec (rx, str, start, flags)
  116. Match the compiled regular expression @var{rx} against
  117. @code{str}. If the optional integer @var{start} argument is
  118. provided, begin matching from that position in the string.
  119. Return a match structure describing the results of the match,
  120. or @code{#f} if no match could be found.
  121. The @var{flags} argument changes the matching behavior. The following
  122. flag values may be supplied, use @code{logior} (@pxref{Bitwise
  123. Operations}) to combine them,
  124. @defvar regexp/notbol
  125. Consider that the @var{start} offset into @var{str} is not the
  126. beginning of a line and should not match operator @samp{^}.
  127. If @var{rx} was created with the @code{regexp/newline} option above,
  128. @samp{^} will still match after a newline in @var{str}.
  129. @end defvar
  130. @defvar regexp/noteol
  131. Consider that the end of @var{str} is not the end of a line and should
  132. not match operator @samp{$}.
  133. If @var{rx} was created with the @code{regexp/newline} option above,
  134. @samp{$} will still match before a newline in @var{str}.
  135. @end defvar
  136. @end deffn
  137. @lisp
  138. ;; Regexp to match uppercase letters
  139. (define r (make-regexp "[A-Z]*"))
  140. ;; Regexp to match letters, ignoring case
  141. (define ri (make-regexp "[A-Z]*" regexp/icase))
  142. ;; Search for bob using regexp r
  143. (match:substring (regexp-exec r "bob"))
  144. @result{} "" ; no match
  145. ;; Search for bob using regexp ri
  146. (match:substring (regexp-exec ri "Bob"))
  147. @result{} "Bob" ; matched case insensitive
  148. @end lisp
  149. @deffn {Scheme Procedure} regexp? obj
  150. @deffnx {C Function} scm_regexp_p (obj)
  151. Return @code{#t} if @var{obj} is a compiled regular expression,
  152. or @code{#f} otherwise.
  153. @end deffn
  154. @sp 1
  155. @deffn {Scheme Procedure} list-matches regexp str [flags]
  156. Return a list of match structures which are the non-overlapping
  157. matches of @var{regexp} in @var{str}. @var{regexp} can be either a
  158. pattern string or a compiled regexp. The @var{flags} argument is as
  159. per @code{regexp-exec} above.
  160. @example
  161. (map match:substring (list-matches "[a-z]+" "abc 42 def 78"))
  162. @result{} ("abc" "def")
  163. @end example
  164. @end deffn
  165. @deffn {Scheme Procedure} fold-matches regexp str init proc [flags]
  166. Apply @var{proc} to the non-overlapping matches of @var{regexp} in
  167. @var{str}, to build a result. @var{regexp} can be either a pattern
  168. string or a compiled regexp. The @var{flags} argument is as per
  169. @code{regexp-exec} above.
  170. @var{proc} is called as @code{(@var{proc} match prev)} where
  171. @var{match} is a match structure and @var{prev} is the previous return
  172. from @var{proc}. For the first call @var{prev} is the given
  173. @var{init} parameter. @code{fold-matches} returns the final value
  174. from @var{proc}.
  175. For example to count matches,
  176. @example
  177. (fold-matches "[a-z][0-9]" "abc x1 def y2" 0
  178. (lambda (match count)
  179. (1+ count)))
  180. @result{} 2
  181. @end example
  182. @end deffn
  183. @sp 1
  184. Regular expressions are commonly used to find patterns in one string
  185. and replace them with the contents of another string. The following
  186. functions are convenient ways to do this.
  187. @c begin (scm-doc-string "regex.scm" "regexp-substitute")
  188. @deffn {Scheme Procedure} regexp-substitute port match item @dots{}
  189. Write to @var{port} selected parts of the match structure @var{match}.
  190. Or if @var{port} is @code{#f} then form a string from those parts and
  191. return that.
  192. Each @var{item} specifies a part to be written, and may be one of the
  193. following,
  194. @itemize @bullet
  195. @item
  196. A string. String arguments are written out verbatim.
  197. @item
  198. An integer. The submatch with that number is written
  199. (@code{match:substring}). Zero is the entire match.
  200. @item
  201. The symbol @samp{pre}. The portion of the matched string preceding
  202. the regexp match is written (@code{match:prefix}).
  203. @item
  204. The symbol @samp{post}. The portion of the matched string following
  205. the regexp match is written (@code{match:suffix}).
  206. @end itemize
  207. For example, changing a match and retaining the text before and after,
  208. @example
  209. (regexp-substitute #f (string-match "[0-9]+" "number 25 is good")
  210. 'pre "37" 'post)
  211. @result{} "number 37 is good"
  212. @end example
  213. Or matching a @sc{yyyymmdd} format date such as @samp{20020828} and
  214. re-ordering and hyphenating the fields.
  215. @lisp
  216. (define date-regex
  217. "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
  218. (define s "Date 20020429 12am.")
  219. (regexp-substitute #f (string-match date-regex s)
  220. 'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
  221. @result{} "Date 04-29-2002 12am. (20020429)"
  222. @end lisp
  223. @end deffn
  224. @c begin (scm-doc-string "regex.scm" "regexp-substitute")
  225. @deffn {Scheme Procedure} regexp-substitute/global port regexp target item@dots{}
  226. @cindex search and replace
  227. Write to @var{port} selected parts of matches of @var{regexp} in
  228. @var{target}. If @var{port} is @code{#f} then form a string from
  229. those parts and return that. @var{regexp} can be a string or a
  230. compiled regex.
  231. This is similar to @code{regexp-substitute}, but allows global
  232. substitutions on @var{target}. Each @var{item} behaves as per
  233. @code{regexp-substitute}, with the following differences,
  234. @itemize @bullet
  235. @item
  236. A function. Called as @code{(@var{item} match)} with the match
  237. structure for the @var{regexp} match, it should return a string to be
  238. written to @var{port}.
  239. @item
  240. The symbol @samp{post}. This doesn't output anything, but instead
  241. causes @code{regexp-substitute/global} to recurse on the unmatched
  242. portion of @var{target}.
  243. This @emph{must} be supplied to perform a global search and replace on
  244. @var{target}; without it @code{regexp-substitute/global} returns after
  245. a single match and output.
  246. @end itemize
  247. For example, to collapse runs of tabs and spaces to a single hyphen
  248. each,
  249. @example
  250. (regexp-substitute/global #f "[ \t]+" "this is the text"
  251. 'pre "-" 'post)
  252. @result{} "this-is-the-text"
  253. @end example
  254. Or using a function to reverse the letters in each word,
  255. @example
  256. (regexp-substitute/global #f "[a-z]+" "to do and not-do"
  257. 'pre (lambda (m) (string-reverse (match:substring m))) 'post)
  258. @result{} "ot od dna ton-od"
  259. @end example
  260. Without the @code{post} symbol, just one regexp match is made. For
  261. example the following is the date example from
  262. @code{regexp-substitute} above, without the need for the separate
  263. @code{string-match} call.
  264. @lisp
  265. (define date-regex
  266. "([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])")
  267. (define s "Date 20020429 12am.")
  268. (regexp-substitute/global #f date-regex s
  269. 'pre 2 "-" 3 "-" 1 'post " (" 0 ")")
  270. @result{} "Date 04-29-2002 12am. (20020429)"
  271. @end lisp
  272. @end deffn
  273. @node Match Structures
  274. @subsection Match Structures
  275. @cindex match structures
  276. A @dfn{match structure} is the object returned by @code{string-match} and
  277. @code{regexp-exec}. It describes which portion of a string, if any,
  278. matched the given regular expression. Match structures include: a
  279. reference to the string that was checked for matches; the starting and
  280. ending positions of the regexp match; and, if the regexp included any
  281. parenthesized subexpressions, the starting and ending positions of each
  282. submatch.
  283. In each of the regexp match functions described below, the @code{match}
  284. argument must be a match structure returned by a previous call to
  285. @code{string-match} or @code{regexp-exec}. Most of these functions
  286. return some information about the original target string that was
  287. matched against a regular expression; we will call that string
  288. @var{target} for easy reference.
  289. @c begin (scm-doc-string "regex.scm" "regexp-match?")
  290. @deffn {Scheme Procedure} regexp-match? obj
  291. Return @code{#t} if @var{obj} is a match structure returned by a
  292. previous call to @code{regexp-exec}, or @code{#f} otherwise.
  293. @end deffn
  294. @c begin (scm-doc-string "regex.scm" "match:substring")
  295. @deffn {Scheme Procedure} match:substring match [n]
  296. Return the portion of @var{target} matched by subexpression number
  297. @var{n}. Submatch 0 (the default) represents the entire regexp match.
  298. If the regular expression as a whole matched, but the subexpression
  299. number @var{n} did not match, return @code{#f}.
  300. @end deffn
  301. @lisp
  302. (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
  303. (match:substring s)
  304. @result{} "2002"
  305. ;; match starting at offset 6 in the string
  306. (match:substring
  307. (string-match "[0-9][0-9][0-9][0-9]" "blah987654" 6))
  308. @result{} "7654"
  309. @end lisp
  310. @c begin (scm-doc-string "regex.scm" "match:start")
  311. @deffn {Scheme Procedure} match:start match [n]
  312. Return the starting position of submatch number @var{n}.
  313. @end deffn
  314. In the following example, the result is 4, since the match starts at
  315. character index 4:
  316. @lisp
  317. (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
  318. (match:start s)
  319. @result{} 4
  320. @end lisp
  321. @c begin (scm-doc-string "regex.scm" "match:end")
  322. @deffn {Scheme Procedure} match:end match [n]
  323. Return the ending position of submatch number @var{n}.
  324. @end deffn
  325. In the following example, the result is 8, since the match runs between
  326. characters 4 and 8 (i.e.@: the ``2002'').
  327. @lisp
  328. (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
  329. (match:end s)
  330. @result{} 8
  331. @end lisp
  332. @c begin (scm-doc-string "regex.scm" "match:prefix")
  333. @deffn {Scheme Procedure} match:prefix match
  334. Return the unmatched portion of @var{target} preceding the regexp match.
  335. @lisp
  336. (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
  337. (match:prefix s)
  338. @result{} "blah"
  339. @end lisp
  340. @end deffn
  341. @c begin (scm-doc-string "regex.scm" "match:suffix")
  342. @deffn {Scheme Procedure} match:suffix match
  343. Return the unmatched portion of @var{target} following the regexp match.
  344. @end deffn
  345. @lisp
  346. (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
  347. (match:suffix s)
  348. @result{} "foo"
  349. @end lisp
  350. @c begin (scm-doc-string "regex.scm" "match:count")
  351. @deffn {Scheme Procedure} match:count match
  352. Return the number of parenthesized subexpressions from @var{match}.
  353. Note that the entire regular expression match itself counts as a
  354. subexpression, and failed submatches are included in the count.
  355. @end deffn
  356. @c begin (scm-doc-string "regex.scm" "match:string")
  357. @deffn {Scheme Procedure} match:string match
  358. Return the original @var{target} string.
  359. @end deffn
  360. @lisp
  361. (define s (string-match "[0-9][0-9][0-9][0-9]" "blah2002foo"))
  362. (match:string s)
  363. @result{} "blah2002foo"
  364. @end lisp
  365. @node Backslash Escapes
  366. @subsection Backslash Escapes
  367. Sometimes you will want a regexp to match characters like @samp{*} or
  368. @samp{$} exactly. For example, to check whether a particular string
  369. represents a menu entry from an Info node, it would be useful to match
  370. it against a regexp like @samp{^* [^:]*::}. However, this won't work;
  371. because the asterisk is a metacharacter, it won't match the @samp{*} at
  372. the beginning of the string. In this case, we want to make the first
  373. asterisk un-magic.
  374. You can do this by preceding the metacharacter with a backslash
  375. character @samp{\}. (This is also called @dfn{quoting} the
  376. metacharacter, and is known as a @dfn{backslash escape}.) When Guile
  377. sees a backslash in a regular expression, it considers the following
  378. glyph to be an ordinary character, no matter what special meaning it
  379. would ordinarily have. Therefore, we can make the above example work by
  380. changing the regexp to @samp{^\* [^:]*::}. The @samp{\*} sequence tells
  381. the regular expression engine to match only a single asterisk in the
  382. target string.
  383. Since the backslash is itself a metacharacter, you may force a regexp to
  384. match a backslash in the target string by preceding the backslash with
  385. itself. For example, to find variable references in a @TeX{} program,
  386. you might want to find occurrences of the string @samp{\let\} followed
  387. by any number of alphabetic characters. The regular expression
  388. @samp{\\let\\[A-Za-z]*} would do this: the double backslashes in the
  389. regexp each match a single backslash in the target string.
  390. @c begin (scm-doc-string "regex.scm" "regexp-quote")
  391. @deffn {Scheme Procedure} regexp-quote str
  392. Quote each special character found in @var{str} with a backslash, and
  393. return the resulting string.
  394. @end deffn
  395. @strong{Very important:} Using backslash escapes in Guile source code
  396. (as in Emacs Lisp or C) can be tricky, because the backslash character
  397. has special meaning for the Guile reader. For example, if Guile
  398. encounters the character sequence @samp{\n} in the middle of a string
  399. while processing Scheme code, it replaces those characters with a
  400. newline character. Similarly, the character sequence @samp{\t} is
  401. replaced by a horizontal tab. Several of these @dfn{escape sequences}
  402. are processed by the Guile reader before your code is executed.
  403. Unrecognized escape sequences are ignored: if the characters @samp{\*}
  404. appear in a string, they will be translated to the single character
  405. @samp{*}.
  406. This translation is obviously undesirable for regular expressions, since
  407. we want to be able to include backslashes in a string in order to
  408. escape regexp metacharacters. Therefore, to make sure that a backslash
  409. is preserved in a string in your Guile program, you must use @emph{two}
  410. consecutive backslashes:
  411. @lisp
  412. (define Info-menu-entry-pattern (make-regexp "^\\* [^:]*"))
  413. @end lisp
  414. The string in this example is preprocessed by the Guile reader before
  415. any code is executed. The resulting argument to @code{make-regexp} is
  416. the string @samp{^\* [^:]*}, which is what we really want.
  417. This also means that in order to write a regular expression that matches
  418. a single backslash character, the regular expression string in the
  419. source code must include @emph{four} backslashes. Each consecutive pair
  420. of backslashes gets translated by the Guile reader to a single
  421. backslash, and the resulting double-backslash is interpreted by the
  422. regexp engine as matching a single backslash character. Hence:
  423. @lisp
  424. (define tex-variable-pattern (make-regexp "\\\\let\\\\=[A-Za-z]*"))
  425. @end lisp
  426. The reason for the unwieldiness of this syntax is historical. Both
  427. regular expression pattern matchers and Unix string processing systems
  428. have traditionally used backslashes with the special meanings
  429. described above. The POSIX regular expression specification and ANSI C
  430. standard both require these semantics. Attempting to abandon either
  431. convention would cause other kinds of compatibility problems, possibly
  432. more severe ones. Therefore, without extending the Scheme reader to
  433. support strings with different quoting conventions (an ungainly and
  434. confusing extension when implemented in other languages), we must adhere
  435. to this cumbersome escape syntax.