api-regex.texi 20 KB

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