api-regex.texi 20 KB

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