]> code.delx.au - gnu-emacs/blob - doc/lispref/searching.texi
Convert consecutive FSF copyright years to ranges.
[gnu-emacs] / doc / lispref / searching.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1995, 1998-1999, 2001-2011
4 @c Free Software Foundation, Inc.
5 @c See the file elisp.texi for copying conditions.
6 @setfilename ../../info/searching
7 @node Searching and Matching, Syntax Tables, Non-ASCII Characters, Top
8 @chapter Searching and Matching
9 @cindex searching
10
11 GNU Emacs provides two ways to search through a buffer for specified
12 text: exact string searches and regular expression searches. After a
13 regular expression search, you can examine the @dfn{match data} to
14 determine which text matched the whole regular expression or various
15 portions of it.
16
17 @menu
18 * String Search:: Search for an exact match.
19 * Searching and Case:: Case-independent or case-significant searching.
20 * Regular Expressions:: Describing classes of strings.
21 * Regexp Search:: Searching for a match for a regexp.
22 * POSIX Regexps:: Searching POSIX-style for the longest match.
23 * Match Data:: Finding out which part of the text matched,
24 after a string or regexp search.
25 * Search and Replace:: Commands that loop, searching and replacing.
26 * Standard Regexps:: Useful regexps for finding sentences, pages,...
27 @end menu
28
29 The @samp{skip-chars@dots{}} functions also perform a kind of searching.
30 @xref{Skipping Characters}. To search for changes in character
31 properties, see @ref{Property Search}.
32
33 @node String Search
34 @section Searching for Strings
35 @cindex string search
36
37 These are the primitive functions for searching through the text in a
38 buffer. They are meant for use in programs, but you may call them
39 interactively. If you do so, they prompt for the search string; the
40 arguments @var{limit} and @var{noerror} are @code{nil}, and @var{repeat}
41 is 1.
42
43 These search functions convert the search string to multibyte if the
44 buffer is multibyte; they convert the search string to unibyte if the
45 buffer is unibyte. @xref{Text Representations}.
46
47 @deffn Command search-forward string &optional limit noerror repeat
48 This function searches forward from point for an exact match for
49 @var{string}. If successful, it sets point to the end of the occurrence
50 found, and returns the new value of point. If no match is found, the
51 value and side effects depend on @var{noerror} (see below).
52 @c Emacs 19 feature
53
54 In the following example, point is initially at the beginning of the
55 line. Then @code{(search-forward "fox")} moves point after the last
56 letter of @samp{fox}:
57
58 @example
59 @group
60 ---------- Buffer: foo ----------
61 @point{}The quick brown fox jumped over the lazy dog.
62 ---------- Buffer: foo ----------
63 @end group
64
65 @group
66 (search-forward "fox")
67 @result{} 20
68
69 ---------- Buffer: foo ----------
70 The quick brown fox@point{} jumped over the lazy dog.
71 ---------- Buffer: foo ----------
72 @end group
73 @end example
74
75 The argument @var{limit} specifies the upper bound to the search. (It
76 must be a position in the current buffer.) No match extending after
77 that position is accepted. If @var{limit} is omitted or @code{nil}, it
78 defaults to the end of the accessible portion of the buffer.
79
80 @kindex search-failed
81 What happens when the search fails depends on the value of
82 @var{noerror}. If @var{noerror} is @code{nil}, a @code{search-failed}
83 error is signaled. If @var{noerror} is @code{t}, @code{search-forward}
84 returns @code{nil} and does nothing. If @var{noerror} is neither
85 @code{nil} nor @code{t}, then @code{search-forward} moves point to the
86 upper bound and returns @code{nil}. (It would be more consistent now to
87 return the new position of point in that case, but some existing
88 programs may depend on a value of @code{nil}.)
89
90 The argument @var{noerror} only affects valid searches which fail to
91 find a match. Invalid arguments cause errors regardless of
92 @var{noerror}.
93
94 If @var{repeat} is supplied (it must be a positive number), then the
95 search is repeated that many times (each time starting at the end of the
96 previous time's match). If these successive searches succeed, the
97 function succeeds, moving point and returning its new value. Otherwise
98 the search fails, with results depending on the value of
99 @var{noerror}, as described above.
100 @end deffn
101
102 @deffn Command search-backward string &optional limit noerror repeat
103 This function searches backward from point for @var{string}. It is
104 just like @code{search-forward} except that it searches backwards and
105 leaves point at the beginning of the match.
106 @end deffn
107
108 @deffn Command word-search-forward string &optional limit noerror repeat
109 This function searches forward from point for a ``word'' match for
110 @var{string}. If it finds a match, it sets point to the end of the
111 match found, and returns the new value of point.
112
113 Word matching regards @var{string} as a sequence of words, disregarding
114 punctuation that separates them. It searches the buffer for the same
115 sequence of words. Each word must be distinct in the buffer (searching
116 for the word @samp{ball} does not match the word @samp{balls}), but the
117 details of punctuation and spacing are ignored (searching for @samp{ball
118 boy} does match @samp{ball. Boy!}).
119
120 In this example, point is initially at the beginning of the buffer; the
121 search leaves it between the @samp{y} and the @samp{!}.
122
123 @example
124 @group
125 ---------- Buffer: foo ----------
126 @point{}He said "Please! Find
127 the ball boy!"
128 ---------- Buffer: foo ----------
129 @end group
130
131 @group
132 (word-search-forward "Please find the ball, boy.")
133 @result{} 35
134
135 ---------- Buffer: foo ----------
136 He said "Please! Find
137 the ball boy@point{}!"
138 ---------- Buffer: foo ----------
139 @end group
140 @end example
141
142 If @var{limit} is non-@code{nil}, it must be a position in the current
143 buffer; it specifies the upper bound to the search. The match found
144 must not extend after that position.
145
146 If @var{noerror} is @code{nil}, then @code{word-search-forward} signals
147 an error if the search fails. If @var{noerror} is @code{t}, then it
148 returns @code{nil} instead of signaling an error. If @var{noerror} is
149 neither @code{nil} nor @code{t}, it moves point to @var{limit} (or the
150 end of the accessible portion of the buffer) and returns @code{nil}.
151
152 If @var{repeat} is non-@code{nil}, then the search is repeated that many
153 times. Point is positioned at the end of the last match.
154 @end deffn
155
156 @deffn Command word-search-forward-lax string &optional limit noerror repeat
157 This command is identical to @code{word-search-forward}, except that
158 the end of @code{string} need not match a word boundary unless it ends
159 in whitespace. For instance, searching for @samp{ball boy} matches
160 @samp{ball boyee}, but does not match @samp{aball boy}.
161 @end deffn
162
163 @deffn Command word-search-backward string &optional limit noerror repeat
164 This function searches backward from point for a word match to
165 @var{string}. This function is just like @code{word-search-forward}
166 except that it searches backward and normally leaves point at the
167 beginning of the match.
168 @end deffn
169
170 @deffn Command word-search-backward-lax string &optional limit noerror repeat
171 This command is identical to @code{word-search-backward}, except that
172 the end of @code{string} need not match a word boundary unless it ends
173 in whitespace.
174 @end deffn
175
176 @node Searching and Case
177 @section Searching and Case
178 @cindex searching and case
179
180 By default, searches in Emacs ignore the case of the text they are
181 searching through; if you specify searching for @samp{FOO}, then
182 @samp{Foo} or @samp{foo} is also considered a match. This applies to
183 regular expressions, too; thus, @samp{[aB]} would match @samp{a} or
184 @samp{A} or @samp{b} or @samp{B}.
185
186 If you do not want this feature, set the variable
187 @code{case-fold-search} to @code{nil}. Then all letters must match
188 exactly, including case. This is a buffer-local variable; altering the
189 variable affects only the current buffer. (@xref{Intro to
190 Buffer-Local}.) Alternatively, you may change the default value of
191 @code{case-fold-search}.
192
193 Note that the user-level incremental search feature handles case
194 distinctions differently. When the search string contains only lower
195 case letters, the search ignores case, but when the search string
196 contains one or more upper case letters, the search becomes
197 case-sensitive. But this has nothing to do with the searching
198 functions used in Lisp code.
199
200 @defopt case-fold-search
201 This buffer-local variable determines whether searches should ignore
202 case. If the variable is @code{nil} they do not ignore case; otherwise
203 they do ignore case.
204 @end defopt
205
206 @defopt case-replace
207 This variable determines whether the higher level replacement
208 functions should preserve case. If the variable is @code{nil}, that
209 means to use the replacement text verbatim. A non-@code{nil} value
210 means to convert the case of the replacement text according to the
211 text being replaced.
212
213 This variable is used by passing it as an argument to the function
214 @code{replace-match}. @xref{Replacing Match}.
215 @end defopt
216
217 @node Regular Expressions
218 @section Regular Expressions
219 @cindex regular expression
220 @cindex regexp
221
222 A @dfn{regular expression}, or @dfn{regexp} for short, is a pattern that
223 denotes a (possibly infinite) set of strings. Searching for matches for
224 a regexp is a very powerful operation. This section explains how to write
225 regexps; the following section says how to search for them.
226
227 @findex re-builder
228 @cindex regular expressions, developing
229 For convenient interactive development of regular expressions, you
230 can use the @kbd{M-x re-builder} command. It provides a convenient
231 interface for creating regular expressions, by giving immediate visual
232 feedback in a separate buffer. As you edit the regexp, all its
233 matches in the target buffer are highlighted. Each parenthesized
234 sub-expression of the regexp is shown in a distinct face, which makes
235 it easier to verify even very complex regexps.
236
237 @menu
238 * Syntax of Regexps:: Rules for writing regular expressions.
239 * Regexp Example:: Illustrates regular expression syntax.
240 * Regexp Functions:: Functions for operating on regular expressions.
241 @end menu
242
243 @node Syntax of Regexps
244 @subsection Syntax of Regular Expressions
245
246 Regular expressions have a syntax in which a few characters are
247 special constructs and the rest are @dfn{ordinary}. An ordinary
248 character is a simple regular expression that matches that character
249 and nothing else. The special characters are @samp{.}, @samp{*},
250 @samp{+}, @samp{?}, @samp{[}, @samp{^}, @samp{$}, and @samp{\}; no new
251 special characters will be defined in the future. The character
252 @samp{]} is special if it ends a character alternative (see later).
253 The character @samp{-} is special inside a character alternative. A
254 @samp{[:} and balancing @samp{:]} enclose a character class inside a
255 character alternative. Any other character appearing in a regular
256 expression is ordinary, unless a @samp{\} precedes it.
257
258 For example, @samp{f} is not a special character, so it is ordinary, and
259 therefore @samp{f} is a regular expression that matches the string
260 @samp{f} and no other string. (It does @emph{not} match the string
261 @samp{fg}, but it does match a @emph{part} of that string.) Likewise,
262 @samp{o} is a regular expression that matches only @samp{o}.@refill
263
264 Any two regular expressions @var{a} and @var{b} can be concatenated. The
265 result is a regular expression that matches a string if @var{a} matches
266 some amount of the beginning of that string and @var{b} matches the rest of
267 the string.@refill
268
269 As a simple example, we can concatenate the regular expressions @samp{f}
270 and @samp{o} to get the regular expression @samp{fo}, which matches only
271 the string @samp{fo}. Still trivial. To do something more powerful, you
272 need to use one of the special regular expression constructs.
273
274 @menu
275 * Regexp Special:: Special characters in regular expressions.
276 * Char Classes:: Character classes used in regular expressions.
277 * Regexp Backslash:: Backslash-sequences in regular expressions.
278 @end menu
279
280 @node Regexp Special
281 @subsubsection Special Characters in Regular Expressions
282
283 Here is a list of the characters that are special in a regular
284 expression.
285
286 @need 800
287 @table @asis
288 @item @samp{.}@: @r{(Period)}
289 @cindex @samp{.} in regexp
290 is a special character that matches any single character except a newline.
291 Using concatenation, we can make regular expressions like @samp{a.b}, which
292 matches any three-character string that begins with @samp{a} and ends with
293 @samp{b}.@refill
294
295 @item @samp{*}
296 @cindex @samp{*} in regexp
297 is not a construct by itself; it is a postfix operator that means to
298 match the preceding regular expression repetitively as many times as
299 possible. Thus, @samp{o*} matches any number of @samp{o}s (including no
300 @samp{o}s).
301
302 @samp{*} always applies to the @emph{smallest} possible preceding
303 expression. Thus, @samp{fo*} has a repeating @samp{o}, not a repeating
304 @samp{fo}. It matches @samp{f}, @samp{fo}, @samp{foo}, and so on.
305
306 The matcher processes a @samp{*} construct by matching, immediately, as
307 many repetitions as can be found. Then it continues with the rest of
308 the pattern. If that fails, backtracking occurs, discarding some of the
309 matches of the @samp{*}-modified construct in the hope that that will
310 make it possible to match the rest of the pattern. For example, in
311 matching @samp{ca*ar} against the string @samp{caaar}, the @samp{a*}
312 first tries to match all three @samp{a}s; but the rest of the pattern is
313 @samp{ar} and there is only @samp{r} left to match, so this try fails.
314 The next alternative is for @samp{a*} to match only two @samp{a}s. With
315 this choice, the rest of the regexp matches successfully.
316
317 @strong{Warning:} Nested repetition operators can run for an
318 indefinitely long time, if they lead to ambiguous matching. For
319 example, trying to match the regular expression @samp{\(x+y*\)*a}
320 against the string @samp{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxz} could
321 take hours before it ultimately fails. Emacs must try each way of
322 grouping the @samp{x}s before concluding that none of them can work.
323 Even worse, @samp{\(x*\)*} can match the null string in infinitely
324 many ways, so it causes an infinite loop. To avoid these problems,
325 check nested repetitions carefully, to make sure that they do not
326 cause combinatorial explosions in backtracking.
327
328 @item @samp{+}
329 @cindex @samp{+} in regexp
330 is a postfix operator, similar to @samp{*} except that it must match
331 the preceding expression at least once. So, for example, @samp{ca+r}
332 matches the strings @samp{car} and @samp{caaaar} but not the string
333 @samp{cr}, whereas @samp{ca*r} matches all three strings.
334
335 @item @samp{?}
336 @cindex @samp{?} in regexp
337 is a postfix operator, similar to @samp{*} except that it must match the
338 preceding expression either once or not at all. For example,
339 @samp{ca?r} matches @samp{car} or @samp{cr}; nothing else.
340
341 @item @samp{*?}, @samp{+?}, @samp{??}
342 @cindex non-greedy repetition characters in regexp
343 These are ``non-greedy'' variants of the operators @samp{*}, @samp{+}
344 and @samp{?}. Where those operators match the largest possible
345 substring (consistent with matching the entire containing expression),
346 the non-greedy variants match the smallest possible substring
347 (consistent with matching the entire containing expression).
348
349 For example, the regular expression @samp{c[ad]*a} when applied to the
350 string @samp{cdaaada} matches the whole string; but the regular
351 expression @samp{c[ad]*?a}, applied to that same string, matches just
352 @samp{cda}. (The smallest possible match here for @samp{[ad]*?} that
353 permits the whole expression to match is @samp{d}.)
354
355 @item @samp{[ @dots{} ]}
356 @cindex character alternative (in regexp)
357 @cindex @samp{[} in regexp
358 @cindex @samp{]} in regexp
359 is a @dfn{character alternative}, which begins with @samp{[} and is
360 terminated by @samp{]}. In the simplest case, the characters between
361 the two brackets are what this character alternative can match.
362
363 Thus, @samp{[ad]} matches either one @samp{a} or one @samp{d}, and
364 @samp{[ad]*} matches any string composed of just @samp{a}s and @samp{d}s
365 (including the empty string). It follows that @samp{c[ad]*r}
366 matches @samp{cr}, @samp{car}, @samp{cdr}, @samp{caddaar}, etc.
367
368 You can also include character ranges in a character alternative, by
369 writing the starting and ending characters with a @samp{-} between them.
370 Thus, @samp{[a-z]} matches any lower-case @acronym{ASCII} letter.
371 Ranges may be intermixed freely with individual characters, as in
372 @samp{[a-z$%.]}, which matches any lower case @acronym{ASCII} letter
373 or @samp{$}, @samp{%} or period.
374
375 Note that the usual regexp special characters are not special inside a
376 character alternative. A completely different set of characters is
377 special inside character alternatives: @samp{]}, @samp{-} and @samp{^}.
378
379 To include a @samp{]} in a character alternative, you must make it the
380 first character. For example, @samp{[]a]} matches @samp{]} or @samp{a}.
381 To include a @samp{-}, write @samp{-} as the first or last character of
382 the character alternative, or put it after a range. Thus, @samp{[]-]}
383 matches both @samp{]} and @samp{-}.
384
385 To include @samp{^} in a character alternative, put it anywhere but at
386 the beginning.
387
388 If a range starts with a unibyte character @var{c} and ends with a
389 multibyte character @var{c2}, the range is divided into two parts: one
390 is @samp{@var{c}..?\377}, the other is @samp{@var{c1}..@var{c2}}, where
391 @var{c1} is the first character of the charset to which @var{c2}
392 belongs.
393
394 A character alternative can also specify named character classes
395 (@pxref{Char Classes}). This is a POSIX feature whose syntax is
396 @samp{[:@var{class}:]}. Using a character class is equivalent to
397 mentioning each of the characters in that class; but the latter is not
398 feasible in practice, since some classes include thousands of
399 different characters.
400
401 @item @samp{[^ @dots{} ]}
402 @cindex @samp{^} in regexp
403 @samp{[^} begins a @dfn{complemented character alternative}. This
404 matches any character except the ones specified. Thus,
405 @samp{[^a-z0-9A-Z]} matches all characters @emph{except} letters and
406 digits.
407
408 @samp{^} is not special in a character alternative unless it is the first
409 character. The character following the @samp{^} is treated as if it
410 were first (in other words, @samp{-} and @samp{]} are not special there).
411
412 A complemented character alternative can match a newline, unless newline is
413 mentioned as one of the characters not to match. This is in contrast to
414 the handling of regexps in programs such as @code{grep}.
415
416 You can specify named character classes, just like in character
417 alternatives. For instance, @samp{[^[:ascii:]]} matches any
418 non-@acronym{ASCII} character. @xref{Char Classes}.
419
420 @item @samp{^}
421 @cindex beginning of line in regexp
422 When matching a buffer, @samp{^} matches the empty string, but only at the
423 beginning of a line in the text being matched (or the beginning of the
424 accessible portion of the buffer). Otherwise it fails to match
425 anything. Thus, @samp{^foo} matches a @samp{foo} that occurs at the
426 beginning of a line.
427
428 When matching a string instead of a buffer, @samp{^} matches at the
429 beginning of the string or after a newline character.
430
431 For historical compatibility reasons, @samp{^} can be used only at the
432 beginning of the regular expression, or after @samp{\(}, @samp{\(?:}
433 or @samp{\|}.
434
435 @item @samp{$}
436 @cindex @samp{$} in regexp
437 @cindex end of line in regexp
438 is similar to @samp{^} but matches only at the end of a line (or the
439 end of the accessible portion of the buffer). Thus, @samp{x+$}
440 matches a string of one @samp{x} or more at the end of a line.
441
442 When matching a string instead of a buffer, @samp{$} matches at the end
443 of the string or before a newline character.
444
445 For historical compatibility reasons, @samp{$} can be used only at the
446 end of the regular expression, or before @samp{\)} or @samp{\|}.
447
448 @item @samp{\}
449 @cindex @samp{\} in regexp
450 has two functions: it quotes the special characters (including
451 @samp{\}), and it introduces additional special constructs.
452
453 Because @samp{\} quotes special characters, @samp{\$} is a regular
454 expression that matches only @samp{$}, and @samp{\[} is a regular
455 expression that matches only @samp{[}, and so on.
456
457 Note that @samp{\} also has special meaning in the read syntax of Lisp
458 strings (@pxref{String Type}), and must be quoted with @samp{\}. For
459 example, the regular expression that matches the @samp{\} character is
460 @samp{\\}. To write a Lisp string that contains the characters
461 @samp{\\}, Lisp syntax requires you to quote each @samp{\} with another
462 @samp{\}. Therefore, the read syntax for a regular expression matching
463 @samp{\} is @code{"\\\\"}.@refill
464 @end table
465
466 @strong{Please note:} For historical compatibility, special characters
467 are treated as ordinary ones if they are in contexts where their special
468 meanings make no sense. For example, @samp{*foo} treats @samp{*} as
469 ordinary since there is no preceding expression on which the @samp{*}
470 can act. It is poor practice to depend on this behavior; quote the
471 special character anyway, regardless of where it appears.@refill
472
473 As a @samp{\} is not special inside a character alternative, it can
474 never remove the special meaning of @samp{-} or @samp{]}. So you
475 should not quote these characters when they have no special meaning
476 either. This would not clarify anything, since backslashes can
477 legitimately precede these characters where they @emph{have} special
478 meaning, as in @samp{[^\]} (@code{"[^\\]"} for Lisp string syntax),
479 which matches any single character except a backslash.
480
481 In practice, most @samp{]} that occur in regular expressions close a
482 character alternative and hence are special. However, occasionally a
483 regular expression may try to match a complex pattern of literal
484 @samp{[} and @samp{]}. In such situations, it sometimes may be
485 necessary to carefully parse the regexp from the start to determine
486 which square brackets enclose a character alternative. For example,
487 @samp{[^][]]} consists of the complemented character alternative
488 @samp{[^][]} (which matches any single character that is not a square
489 bracket), followed by a literal @samp{]}.
490
491 The exact rules are that at the beginning of a regexp, @samp{[} is
492 special and @samp{]} not. This lasts until the first unquoted
493 @samp{[}, after which we are in a character alternative; @samp{[} is
494 no longer special (except when it starts a character class) but @samp{]}
495 is special, unless it immediately follows the special @samp{[} or that
496 @samp{[} followed by a @samp{^}. This lasts until the next special
497 @samp{]} that does not end a character class. This ends the character
498 alternative and restores the ordinary syntax of regular expressions;
499 an unquoted @samp{[} is special again and a @samp{]} not.
500
501 @node Char Classes
502 @subsubsection Character Classes
503 @cindex character classes in regexp
504
505 Here is a table of the classes you can use in a character alternative,
506 and what they mean:
507
508 @table @samp
509 @item [:ascii:]
510 This matches any @acronym{ASCII} character (codes 0--127).
511 @item [:alnum:]
512 This matches any letter or digit. (At present, for multibyte
513 characters, it matches anything that has word syntax.)
514 @item [:alpha:]
515 This matches any letter. (At present, for multibyte characters, it
516 matches anything that has word syntax.)
517 @item [:blank:]
518 This matches space and tab only.
519 @item [:cntrl:]
520 This matches any @acronym{ASCII} control character.
521 @item [:digit:]
522 This matches @samp{0} through @samp{9}. Thus, @samp{[-+[:digit:]]}
523 matches any digit, as well as @samp{+} and @samp{-}.
524 @item [:graph:]
525 This matches graphic characters---everything except @acronym{ASCII} control
526 characters, space, and the delete character.
527 @item [:lower:]
528 This matches any lower-case letter, as determined by the current case
529 table (@pxref{Case Tables}). If @code{case-fold-search} is
530 non-@code{nil}, this also matches any upper-case letter.
531 @item [:multibyte:]
532 This matches any multibyte character (@pxref{Text Representations}).
533 @item [:nonascii:]
534 This matches any non-@acronym{ASCII} character.
535 @item [:print:]
536 This matches printing characters---everything except @acronym{ASCII} control
537 characters and the delete character.
538 @item [:punct:]
539 This matches any punctuation character. (At present, for multibyte
540 characters, it matches anything that has non-word syntax.)
541 @item [:space:]
542 This matches any character that has whitespace syntax
543 (@pxref{Syntax Class Table}).
544 @item [:unibyte:]
545 This matches any unibyte character (@pxref{Text Representations}).
546 @item [:upper:]
547 This matches any upper-case letter, as determined by the current case
548 table (@pxref{Case Tables}). If @code{case-fold-search} is
549 non-@code{nil}, this also matches any lower-case letter.
550 @item [:word:]
551 This matches any character that has word syntax (@pxref{Syntax Class
552 Table}).
553 @item [:xdigit:]
554 This matches the hexadecimal digits: @samp{0} through @samp{9}, @samp{a}
555 through @samp{f} and @samp{A} through @samp{F}.
556 @end table
557
558 @node Regexp Backslash
559 @subsubsection Backslash Constructs in Regular Expressions
560
561 For the most part, @samp{\} followed by any character matches only
562 that character. However, there are several exceptions: certain
563 two-character sequences starting with @samp{\} that have special
564 meanings. (The character after the @samp{\} in such a sequence is
565 always ordinary when used on its own.) Here is a table of the special
566 @samp{\} constructs.
567
568 @table @samp
569 @item \|
570 @cindex @samp{|} in regexp
571 @cindex regexp alternative
572 specifies an alternative.
573 Two regular expressions @var{a} and @var{b} with @samp{\|} in
574 between form an expression that matches anything that either @var{a} or
575 @var{b} matches.@refill
576
577 Thus, @samp{foo\|bar} matches either @samp{foo} or @samp{bar}
578 but no other string.@refill
579
580 @samp{\|} applies to the largest possible surrounding expressions. Only a
581 surrounding @samp{\( @dots{} \)} grouping can limit the grouping power of
582 @samp{\|}.@refill
583
584 If you need full backtracking capability to handle multiple uses of
585 @samp{\|}, use the POSIX regular expression functions (@pxref{POSIX
586 Regexps}).
587
588 @item \@{@var{m}\@}
589 is a postfix operator that repeats the previous pattern exactly @var{m}
590 times. Thus, @samp{x\@{5\@}} matches the string @samp{xxxxx}
591 and nothing else. @samp{c[ad]\@{3\@}r} matches string such as
592 @samp{caaar}, @samp{cdddr}, @samp{cadar}, and so on.
593
594 @item \@{@var{m},@var{n}\@}
595 is a more general postfix operator that specifies repetition with a
596 minimum of @var{m} repeats and a maximum of @var{n} repeats. If @var{m}
597 is omitted, the minimum is 0; if @var{n} is omitted, there is no
598 maximum.
599
600 For example, @samp{c[ad]\@{1,2\@}r} matches the strings @samp{car},
601 @samp{cdr}, @samp{caar}, @samp{cadr}, @samp{cdar}, and @samp{cddr}, and
602 nothing else.@*
603 @samp{\@{0,1\@}} or @samp{\@{,1\@}} is equivalent to @samp{?}.@*
604 @samp{\@{0,\@}} or @samp{\@{,\@}} is equivalent to @samp{*}.@*
605 @samp{\@{1,\@}} is equivalent to @samp{+}.
606
607 @item \( @dots{} \)
608 @cindex @samp{(} in regexp
609 @cindex @samp{)} in regexp
610 @cindex regexp grouping
611 is a grouping construct that serves three purposes:
612
613 @enumerate
614 @item
615 To enclose a set of @samp{\|} alternatives for other operations. Thus,
616 the regular expression @samp{\(foo\|bar\)x} matches either @samp{foox}
617 or @samp{barx}.
618
619 @item
620 To enclose a complicated expression for the postfix operators @samp{*},
621 @samp{+} and @samp{?} to operate on. Thus, @samp{ba\(na\)*} matches
622 @samp{ba}, @samp{bana}, @samp{banana}, @samp{bananana}, etc., with any
623 number (zero or more) of @samp{na} strings.
624
625 @item
626 To record a matched substring for future reference with
627 @samp{\@var{digit}} (see below).
628 @end enumerate
629
630 This last application is not a consequence of the idea of a
631 parenthetical grouping; it is a separate feature that was assigned as a
632 second meaning to the same @samp{\( @dots{} \)} construct because, in
633 practice, there was usually no conflict between the two meanings. But
634 occasionally there is a conflict, and that led to the introduction of
635 shy groups.
636
637 @item \(?: @dots{} \)
638 @cindex shy groups
639 @cindex non-capturing group
640 @cindex unnumbered group
641 @cindex @samp{(?:} in regexp
642 is the @dfn{shy group} construct. A shy group serves the first two
643 purposes of an ordinary group (controlling the nesting of other
644 operators), but it does not get a number, so you cannot refer back to
645 its value with @samp{\@var{digit}}. Shy groups are particularly
646 useful for mechanically-constructed regular expressions, because they
647 can be added automatically without altering the numbering of ordinary,
648 non-shy groups.
649
650 Shy groups are also called @dfn{non-capturing} or @dfn{unnumbered
651 groups}.
652
653 @item \(?@var{num}: @dots{} \)
654 is the @dfn{explicitly numbered group} construct. Normal groups get
655 their number implicitly, based on their position, which can be
656 inconvenient. This construct allows you to force a particular group
657 number. There is no particular restriction on the numbering,
658 e.g.@: you can have several groups with the same number in which case
659 the last one to match (i.e.@: the rightmost match) will win.
660 Implicitly numbered groups always get the smallest integer larger than
661 the one of any previous group.
662
663 @item \@var{digit}
664 matches the same text that matched the @var{digit}th occurrence of a
665 grouping (@samp{\( @dots{} \)}) construct.
666
667 In other words, after the end of a group, the matcher remembers the
668 beginning and end of the text matched by that group. Later on in the
669 regular expression you can use @samp{\} followed by @var{digit} to
670 match that same text, whatever it may have been.
671
672 The strings matching the first nine grouping constructs appearing in
673 the entire regular expression passed to a search or matching function
674 are assigned numbers 1 through 9 in the order that the open
675 parentheses appear in the regular expression. So you can use
676 @samp{\1} through @samp{\9} to refer to the text matched by the
677 corresponding grouping constructs.
678
679 For example, @samp{\(.*\)\1} matches any newline-free string that is
680 composed of two identical halves. The @samp{\(.*\)} matches the first
681 half, which may be anything, but the @samp{\1} that follows must match
682 the same exact text.
683
684 If a @samp{\( @dots{} \)} construct matches more than once (which can
685 happen, for instance, if it is followed by @samp{*}), only the last
686 match is recorded.
687
688 If a particular grouping construct in the regular expression was never
689 matched---for instance, if it appears inside of an alternative that
690 wasn't used, or inside of a repetition that repeated zero times---then
691 the corresponding @samp{\@var{digit}} construct never matches
692 anything. To use an artificial example, @samp{\(foo\(b*\)\|lose\)\2}
693 cannot match @samp{lose}: the second alternative inside the larger
694 group matches it, but then @samp{\2} is undefined and can't match
695 anything. But it can match @samp{foobb}, because the first
696 alternative matches @samp{foob} and @samp{\2} matches @samp{b}.
697
698 @item \w
699 @cindex @samp{\w} in regexp
700 matches any word-constituent character. The editor syntax table
701 determines which characters these are. @xref{Syntax Tables}.
702
703 @item \W
704 @cindex @samp{\W} in regexp
705 matches any character that is not a word constituent.
706
707 @item \s@var{code}
708 @cindex @samp{\s} in regexp
709 matches any character whose syntax is @var{code}. Here @var{code} is a
710 character that represents a syntax code: thus, @samp{w} for word
711 constituent, @samp{-} for whitespace, @samp{(} for open parenthesis,
712 etc. To represent whitespace syntax, use either @samp{-} or a space
713 character. @xref{Syntax Class Table}, for a list of syntax codes and
714 the characters that stand for them.
715
716 @item \S@var{code}
717 @cindex @samp{\S} in regexp
718 matches any character whose syntax is not @var{code}.
719
720 @item \c@var{c}
721 matches any character whose category is @var{c}. Here @var{c} is a
722 character that represents a category: thus, @samp{c} for Chinese
723 characters or @samp{g} for Greek characters in the standard category
724 table.
725
726 @item \C@var{c}
727 matches any character whose category is not @var{c}.
728 @end table
729
730 The following regular expression constructs match the empty string---that is,
731 they don't use up any characters---but whether they match depends on the
732 context. For all, the beginning and end of the accessible portion of
733 the buffer are treated as if they were the actual beginning and end of
734 the buffer.
735
736 @table @samp
737 @item \`
738 @cindex @samp{\`} in regexp
739 matches the empty string, but only at the beginning
740 of the buffer or string being matched against.
741
742 @item \'
743 @cindex @samp{\'} in regexp
744 matches the empty string, but only at the end of
745 the buffer or string being matched against.
746
747 @item \=
748 @cindex @samp{\=} in regexp
749 matches the empty string, but only at point.
750 (This construct is not defined when matching against a string.)
751
752 @item \b
753 @cindex @samp{\b} in regexp
754 matches the empty string, but only at the beginning or
755 end of a word. Thus, @samp{\bfoo\b} matches any occurrence of
756 @samp{foo} as a separate word. @samp{\bballs?\b} matches
757 @samp{ball} or @samp{balls} as a separate word.@refill
758
759 @samp{\b} matches at the beginning or end of the buffer (or string)
760 regardless of what text appears next to it.
761
762 @item \B
763 @cindex @samp{\B} in regexp
764 matches the empty string, but @emph{not} at the beginning or
765 end of a word, nor at the beginning or end of the buffer (or string).
766
767 @item \<
768 @cindex @samp{\<} in regexp
769 matches the empty string, but only at the beginning of a word.
770 @samp{\<} matches at the beginning of the buffer (or string) only if a
771 word-constituent character follows.
772
773 @item \>
774 @cindex @samp{\>} in regexp
775 matches the empty string, but only at the end of a word. @samp{\>}
776 matches at the end of the buffer (or string) only if the contents end
777 with a word-constituent character.
778
779 @item \_<
780 @cindex @samp{\_<} in regexp
781 matches the empty string, but only at the beginning of a symbol. A
782 symbol is a sequence of one or more word or symbol constituent
783 characters. @samp{\_<} matches at the beginning of the buffer (or
784 string) only if a symbol-constituent character follows.
785
786 @item \_>
787 @cindex @samp{\_>} in regexp
788 matches the empty string, but only at the end of a symbol. @samp{\_>}
789 matches at the end of the buffer (or string) only if the contents end
790 with a symbol-constituent character.
791 @end table
792
793 @kindex invalid-regexp
794 Not every string is a valid regular expression. For example, a string
795 that ends inside a character alternative without terminating @samp{]}
796 is invalid, and so is a string that ends with a single @samp{\}. If
797 an invalid regular expression is passed to any of the search functions,
798 an @code{invalid-regexp} error is signaled.
799
800 @node Regexp Example
801 @comment node-name, next, previous, up
802 @subsection Complex Regexp Example
803
804 Here is a complicated regexp which was formerly used by Emacs to
805 recognize the end of a sentence together with any whitespace that
806 follows. (Nowadays Emacs uses a similar but more complex default
807 regexp constructed by the function @code{sentence-end}.
808 @xref{Standard Regexps}.)
809
810 First, we show the regexp as a string in Lisp syntax to distinguish
811 spaces from tab characters. The string constant begins and ends with a
812 double-quote. @samp{\"} stands for a double-quote as part of the
813 string, @samp{\\} for a backslash as part of the string, @samp{\t} for a
814 tab and @samp{\n} for a newline.
815
816 @example
817 "[.?!][]\"')@}]*\\($\\| $\\|\t\\|@ @ \\)[ \t\n]*"
818 @end example
819
820 @noindent
821 In contrast, if you evaluate this string, you will see the following:
822
823 @example
824 @group
825 "[.?!][]\"')@}]*\\($\\| $\\|\t\\|@ @ \\)[ \t\n]*"
826 @result{} "[.?!][]\"')@}]*\\($\\| $\\| \\|@ @ \\)[
827 ]*"
828 @end group
829 @end example
830
831 @noindent
832 In this output, tab and newline appear as themselves.
833
834 This regular expression contains four parts in succession and can be
835 deciphered as follows:
836
837 @table @code
838 @item [.?!]
839 The first part of the pattern is a character alternative that matches
840 any one of three characters: period, question mark, and exclamation
841 mark. The match must begin with one of these three characters. (This
842 is one point where the new default regexp used by Emacs differs from
843 the old. The new value also allows some non-@acronym{ASCII}
844 characters that end a sentence without any following whitespace.)
845
846 @item []\"')@}]*
847 The second part of the pattern matches any closing braces and quotation
848 marks, zero or more of them, that may follow the period, question mark
849 or exclamation mark. The @code{\"} is Lisp syntax for a double-quote in
850 a string. The @samp{*} at the end indicates that the immediately
851 preceding regular expression (a character alternative, in this case) may be
852 repeated zero or more times.
853
854 @item \\($\\|@ $\\|\t\\|@ @ \\)
855 The third part of the pattern matches the whitespace that follows the
856 end of a sentence: the end of a line (optionally with a space), or a
857 tab, or two spaces. The double backslashes mark the parentheses and
858 vertical bars as regular expression syntax; the parentheses delimit a
859 group and the vertical bars separate alternatives. The dollar sign is
860 used to match the end of a line.
861
862 @item [ \t\n]*
863 Finally, the last part of the pattern matches any additional whitespace
864 beyond the minimum needed to end a sentence.
865 @end table
866
867 @node Regexp Functions
868 @subsection Regular Expression Functions
869
870 These functions operate on regular expressions.
871
872 @defun regexp-quote string
873 This function returns a regular expression whose only exact match is
874 @var{string}. Using this regular expression in @code{looking-at} will
875 succeed only if the next characters in the buffer are @var{string};
876 using it in a search function will succeed if the text being searched
877 contains @var{string}.
878
879 This allows you to request an exact string match or search when calling
880 a function that wants a regular expression.
881
882 @example
883 @group
884 (regexp-quote "^The cat$")
885 @result{} "\\^The cat\\$"
886 @end group
887 @end example
888
889 One use of @code{regexp-quote} is to combine an exact string match with
890 context described as a regular expression. For example, this searches
891 for the string that is the value of @var{string}, surrounded by
892 whitespace:
893
894 @example
895 @group
896 (re-search-forward
897 (concat "\\s-" (regexp-quote string) "\\s-"))
898 @end group
899 @end example
900 @end defun
901
902 @defun regexp-opt strings &optional paren
903 This function returns an efficient regular expression that will match
904 any of the strings in the list @var{strings}. This is useful when you
905 need to make matching or searching as fast as possible---for example,
906 for Font Lock mode.
907
908 If the optional argument @var{paren} is non-@code{nil}, then the
909 returned regular expression is always enclosed by at least one
910 parentheses-grouping construct. If @var{paren} is @code{words}, then
911 that construct is additionally surrounded by @samp{\<} and @samp{\>};
912 alternatively, if @var{paren} is @code{symbols}, then that construct
913 is additionally surrounded by @samp{\_<} and @samp{\_>}
914 (@code{symbols} is often appropriate when matching
915 programming-language keywords and the like).
916
917 This simplified definition of @code{regexp-opt} produces a
918 regular expression which is equivalent to the actual value
919 (but not as efficient):
920
921 @example
922 (defun regexp-opt (strings paren)
923 (let ((open-paren (if paren "\\(" ""))
924 (close-paren (if paren "\\)" "")))
925 (concat open-paren
926 (mapconcat 'regexp-quote strings "\\|")
927 close-paren)))
928 @end example
929 @end defun
930
931 @defun regexp-opt-depth regexp
932 This function returns the total number of grouping constructs
933 (parenthesized expressions) in @var{regexp}. This does not include
934 shy groups (@pxref{Regexp Backslash}).
935 @end defun
936
937 @node Regexp Search
938 @section Regular Expression Searching
939 @cindex regular expression searching
940 @cindex regexp searching
941 @cindex searching for regexp
942
943 In GNU Emacs, you can search for the next match for a regular
944 expression either incrementally or not. For incremental search
945 commands, see @ref{Regexp Search, , Regular Expression Search, emacs,
946 The GNU Emacs Manual}. Here we describe only the search functions
947 useful in programs. The principal one is @code{re-search-forward}.
948
949 These search functions convert the regular expression to multibyte if
950 the buffer is multibyte; they convert the regular expression to unibyte
951 if the buffer is unibyte. @xref{Text Representations}.
952
953 @deffn Command re-search-forward regexp &optional limit noerror repeat
954 This function searches forward in the current buffer for a string of
955 text that is matched by the regular expression @var{regexp}. The
956 function skips over any amount of text that is not matched by
957 @var{regexp}, and leaves point at the end of the first match found.
958 It returns the new value of point.
959
960 If @var{limit} is non-@code{nil}, it must be a position in the current
961 buffer. It specifies the upper bound to the search. No match
962 extending after that position is accepted.
963
964 If @var{repeat} is supplied, it must be a positive number; the search
965 is repeated that many times; each repetition starts at the end of the
966 previous match. If all these successive searches succeed, the search
967 succeeds, moving point and returning its new value. Otherwise the
968 search fails. What @code{re-search-forward} does when the search
969 fails depends on the value of @var{noerror}:
970
971 @table @asis
972 @item @code{nil}
973 Signal a @code{search-failed} error.
974 @item @code{t}
975 Do nothing and return @code{nil}.
976 @item anything else
977 Move point to @var{limit} (or the end of the accessible portion of the
978 buffer) and return @code{nil}.
979 @end table
980
981 In the following example, point is initially before the @samp{T}.
982 Evaluating the search call moves point to the end of that line (between
983 the @samp{t} of @samp{hat} and the newline).
984
985 @example
986 @group
987 ---------- Buffer: foo ----------
988 I read "@point{}The cat in the hat
989 comes back" twice.
990 ---------- Buffer: foo ----------
991 @end group
992
993 @group
994 (re-search-forward "[a-z]+" nil t 5)
995 @result{} 27
996
997 ---------- Buffer: foo ----------
998 I read "The cat in the hat@point{}
999 comes back" twice.
1000 ---------- Buffer: foo ----------
1001 @end group
1002 @end example
1003 @end deffn
1004
1005 @deffn Command re-search-backward regexp &optional limit noerror repeat
1006 This function searches backward in the current buffer for a string of
1007 text that is matched by the regular expression @var{regexp}, leaving
1008 point at the beginning of the first text found.
1009
1010 This function is analogous to @code{re-search-forward}, but they are not
1011 simple mirror images. @code{re-search-forward} finds the match whose
1012 beginning is as close as possible to the starting point. If
1013 @code{re-search-backward} were a perfect mirror image, it would find the
1014 match whose end is as close as possible. However, in fact it finds the
1015 match whose beginning is as close as possible (and yet ends before the
1016 starting point). The reason for this is that matching a regular
1017 expression at a given spot always works from beginning to end, and
1018 starts at a specified beginning position.
1019
1020 A true mirror-image of @code{re-search-forward} would require a special
1021 feature for matching regular expressions from end to beginning. It's
1022 not worth the trouble of implementing that.
1023 @end deffn
1024
1025 @defun string-match regexp string &optional start
1026 This function returns the index of the start of the first match for
1027 the regular expression @var{regexp} in @var{string}, or @code{nil} if
1028 there is no match. If @var{start} is non-@code{nil}, the search starts
1029 at that index in @var{string}.
1030
1031 For example,
1032
1033 @example
1034 @group
1035 (string-match
1036 "quick" "The quick brown fox jumped quickly.")
1037 @result{} 4
1038 @end group
1039 @group
1040 (string-match
1041 "quick" "The quick brown fox jumped quickly." 8)
1042 @result{} 27
1043 @end group
1044 @end example
1045
1046 @noindent
1047 The index of the first character of the
1048 string is 0, the index of the second character is 1, and so on.
1049
1050 After this function returns, the index of the first character beyond
1051 the match is available as @code{(match-end 0)}. @xref{Match Data}.
1052
1053 @example
1054 @group
1055 (string-match
1056 "quick" "The quick brown fox jumped quickly." 8)
1057 @result{} 27
1058 @end group
1059
1060 @group
1061 (match-end 0)
1062 @result{} 32
1063 @end group
1064 @end example
1065 @end defun
1066
1067 @defun string-match-p regexp string &optional start
1068 This predicate function does what @code{string-match} does, but it
1069 avoids modifying the match data.
1070 @end defun
1071
1072 @defun looking-at regexp
1073 This function determines whether the text in the current buffer directly
1074 following point matches the regular expression @var{regexp}. ``Directly
1075 following'' means precisely that: the search is ``anchored'' and it can
1076 succeed only starting with the first character following point. The
1077 result is @code{t} if so, @code{nil} otherwise.
1078
1079 This function does not move point, but it updates the match data, which
1080 you can access using @code{match-beginning} and @code{match-end}.
1081 @xref{Match Data}. If you need to test for a match without modifying
1082 the match data, use @code{looking-at-p}, described below.
1083
1084 In this example, point is located directly before the @samp{T}. If it
1085 were anywhere else, the result would be @code{nil}.
1086
1087 @example
1088 @group
1089 ---------- Buffer: foo ----------
1090 I read "@point{}The cat in the hat
1091 comes back" twice.
1092 ---------- Buffer: foo ----------
1093
1094 (looking-at "The cat in the hat$")
1095 @result{} t
1096 @end group
1097 @end example
1098 @end defun
1099
1100 @defun looking-back regexp &optional limit greedy
1101 This function returns @code{t} if @var{regexp} matches text before
1102 point, ending at point, and @code{nil} otherwise.
1103
1104 Because regular expression matching works only going forward, this is
1105 implemented by searching backwards from point for a match that ends at
1106 point. That can be quite slow if it has to search a long distance.
1107 You can bound the time required by specifying @var{limit}, which says
1108 not to search before @var{limit}. In this case, the match that is
1109 found must begin at or after @var{limit}.
1110
1111 If @var{greedy} is non-@code{nil}, this function extends the match
1112 backwards as far as possible, stopping when a single additional
1113 previous character cannot be part of a match for regexp. When the
1114 match is extended, its starting position is allowed to occur before
1115 @var{limit}.
1116
1117 @example
1118 @group
1119 ---------- Buffer: foo ----------
1120 I read "@point{}The cat in the hat
1121 comes back" twice.
1122 ---------- Buffer: foo ----------
1123
1124 (looking-back "read \"" 3)
1125 @result{} t
1126 (looking-back "read \"" 4)
1127 @result{} nil
1128 @end group
1129 @end example
1130 @end defun
1131
1132 @defun looking-at-p regexp
1133 This predicate function works like @code{looking-at}, but without
1134 updating the match data.
1135 @end defun
1136
1137 @defvar search-spaces-regexp
1138 If this variable is non-@code{nil}, it should be a regular expression
1139 that says how to search for whitespace. In that case, any group of
1140 spaces in a regular expression being searched for stands for use of
1141 this regular expression. However, spaces inside of constructs such as
1142 @samp{[@dots{}]} and @samp{*}, @samp{+}, @samp{?} are not affected by
1143 @code{search-spaces-regexp}.
1144
1145 Since this variable affects all regular expression search and match
1146 constructs, you should bind it temporarily for as small as possible
1147 a part of the code.
1148 @end defvar
1149
1150 @node POSIX Regexps
1151 @section POSIX Regular Expression Searching
1152
1153 The usual regular expression functions do backtracking when necessary
1154 to handle the @samp{\|} and repetition constructs, but they continue
1155 this only until they find @emph{some} match. Then they succeed and
1156 report the first match found.
1157
1158 This section describes alternative search functions which perform the
1159 full backtracking specified by the POSIX standard for regular expression
1160 matching. They continue backtracking until they have tried all
1161 possibilities and found all matches, so they can report the longest
1162 match, as required by POSIX. This is much slower, so use these
1163 functions only when you really need the longest match.
1164
1165 The POSIX search and match functions do not properly support the
1166 non-greedy repetition operators (@pxref{Regexp Special, non-greedy}).
1167 This is because POSIX backtracking conflicts with the semantics of
1168 non-greedy repetition.
1169
1170 @deffn Command posix-search-forward regexp &optional limit noerror repeat
1171 This is like @code{re-search-forward} except that it performs the full
1172 backtracking specified by the POSIX standard for regular expression
1173 matching.
1174 @end deffn
1175
1176 @deffn Command posix-search-backward regexp &optional limit noerror repeat
1177 This is like @code{re-search-backward} except that it performs the full
1178 backtracking specified by the POSIX standard for regular expression
1179 matching.
1180 @end deffn
1181
1182 @defun posix-looking-at regexp
1183 This is like @code{looking-at} except that it performs the full
1184 backtracking specified by the POSIX standard for regular expression
1185 matching.
1186 @end defun
1187
1188 @defun posix-string-match regexp string &optional start
1189 This is like @code{string-match} except that it performs the full
1190 backtracking specified by the POSIX standard for regular expression
1191 matching.
1192 @end defun
1193
1194 @node Match Data
1195 @section The Match Data
1196 @cindex match data
1197
1198 Emacs keeps track of the start and end positions of the segments of
1199 text found during a search; this is called the @dfn{match data}.
1200 Thanks to the match data, you can search for a complex pattern, such
1201 as a date in a mail message, and then extract parts of the match under
1202 control of the pattern.
1203
1204 Because the match data normally describe the most recent search only,
1205 you must be careful not to do another search inadvertently between the
1206 search you wish to refer back to and the use of the match data. If you
1207 can't avoid another intervening search, you must save and restore the
1208 match data around it, to prevent it from being overwritten.
1209
1210 @menu
1211 * Replacing Match:: Replacing a substring that was matched.
1212 * Simple Match Data:: Accessing single items of match data,
1213 such as where a particular subexpression started.
1214 * Entire Match Data:: Accessing the entire match data at once, as a list.
1215 * Saving Match Data:: Saving and restoring the match data.
1216 @end menu
1217
1218 @node Replacing Match
1219 @subsection Replacing the Text that Matched
1220 @cindex replace matched text
1221
1222 This function replaces all or part of the text matched by the last
1223 search. It works by means of the match data.
1224
1225 @cindex case in replacements
1226 @defun replace-match replacement &optional fixedcase literal string subexp
1227 This function replaces the text in the buffer (or in @var{string}) that
1228 was matched by the last search. It replaces that text with
1229 @var{replacement}.
1230
1231 If you did the last search in a buffer, you should specify @code{nil}
1232 for @var{string} and make sure that the current buffer when you call
1233 @code{replace-match} is the one in which you did the searching or
1234 matching. Then @code{replace-match} does the replacement by editing
1235 the buffer; it leaves point at the end of the replacement text, and
1236 returns @code{t}.
1237
1238 If you did the search in a string, pass the same string as @var{string}.
1239 Then @code{replace-match} does the replacement by constructing and
1240 returning a new string.
1241
1242 If @var{fixedcase} is non-@code{nil}, then @code{replace-match} uses
1243 the replacement text without case conversion; otherwise, it converts
1244 the replacement text depending upon the capitalization of the text to
1245 be replaced. If the original text is all upper case, this converts
1246 the replacement text to upper case. If all words of the original text
1247 are capitalized, this capitalizes all the words of the replacement
1248 text. If all the words are one-letter and they are all upper case,
1249 they are treated as capitalized words rather than all-upper-case
1250 words.
1251
1252 If @var{literal} is non-@code{nil}, then @var{replacement} is inserted
1253 exactly as it is, the only alterations being case changes as needed.
1254 If it is @code{nil} (the default), then the character @samp{\} is treated
1255 specially. If a @samp{\} appears in @var{replacement}, then it must be
1256 part of one of the following sequences:
1257
1258 @table @asis
1259 @item @samp{\&}
1260 @cindex @samp{&} in replacement
1261 @samp{\&} stands for the entire text being replaced.
1262
1263 @item @samp{\@var{n}}
1264 @cindex @samp{\@var{n}} in replacement
1265 @samp{\@var{n}}, where @var{n} is a digit, stands for the text that
1266 matched the @var{n}th subexpression in the original regexp.
1267 Subexpressions are those expressions grouped inside @samp{\(@dots{}\)}.
1268 If the @var{n}th subexpression never matched, an empty string is substituted.
1269
1270 @item @samp{\\}
1271 @cindex @samp{\} in replacement
1272 @samp{\\} stands for a single @samp{\} in the replacement text.
1273 @end table
1274
1275 These substitutions occur after case conversion, if any,
1276 so the strings they substitute are never case-converted.
1277
1278 If @var{subexp} is non-@code{nil}, that says to replace just
1279 subexpression number @var{subexp} of the regexp that was matched, not
1280 the entire match. For example, after matching @samp{foo \(ba*r\)},
1281 calling @code{replace-match} with 1 as @var{subexp} means to replace
1282 just the text that matched @samp{\(ba*r\)}.
1283 @end defun
1284
1285 @defun match-substitute-replacement replacement &optional fixedcase literal string subexp
1286 This function returns the text that would be inserted into the buffer
1287 by @code{replace-match}, but without modifying the buffer. It is
1288 useful if you want to present the user with actual replacement result,
1289 with constructs like @samp{\@var{n}} or @samp{\&} substituted with
1290 matched groups. Arguments @var{replacement} and optional
1291 @var{fixedcase}, @var{literal}, @var{string} and @var{subexp} have the
1292 same meaning as for @code{replace-match}.
1293 @end defun
1294
1295 @node Simple Match Data
1296 @subsection Simple Match Data Access
1297
1298 This section explains how to use the match data to find out what was
1299 matched by the last search or match operation, if it succeeded.
1300
1301 You can ask about the entire matching text, or about a particular
1302 parenthetical subexpression of a regular expression. The @var{count}
1303 argument in the functions below specifies which. If @var{count} is
1304 zero, you are asking about the entire match. If @var{count} is
1305 positive, it specifies which subexpression you want.
1306
1307 Recall that the subexpressions of a regular expression are those
1308 expressions grouped with escaped parentheses, @samp{\(@dots{}\)}. The
1309 @var{count}th subexpression is found by counting occurrences of
1310 @samp{\(} from the beginning of the whole regular expression. The first
1311 subexpression is numbered 1, the second 2, and so on. Only regular
1312 expressions can have subexpressions---after a simple string search, the
1313 only information available is about the entire match.
1314
1315 Every successful search sets the match data. Therefore, you should
1316 query the match data immediately after searching, before calling any
1317 other function that might perform another search. Alternatively, you
1318 may save and restore the match data (@pxref{Saving Match Data}) around
1319 the call to functions that could perform another search.
1320
1321 A search which fails may or may not alter the match data. In the
1322 past, a failing search did not do this, but we may change it in the
1323 future. So don't try to rely on the value of the match data after
1324 a failing search.
1325
1326 @defun match-string count &optional in-string
1327 This function returns, as a string, the text matched in the last search
1328 or match operation. It returns the entire text if @var{count} is zero,
1329 or just the portion corresponding to the @var{count}th parenthetical
1330 subexpression, if @var{count} is positive.
1331
1332 If the last such operation was done against a string with
1333 @code{string-match}, then you should pass the same string as the
1334 argument @var{in-string}. After a buffer search or match,
1335 you should omit @var{in-string} or pass @code{nil} for it; but you
1336 should make sure that the current buffer when you call
1337 @code{match-string} is the one in which you did the searching or
1338 matching.
1339
1340 The value is @code{nil} if @var{count} is out of range, or for a
1341 subexpression inside a @samp{\|} alternative that wasn't used or a
1342 repetition that repeated zero times.
1343 @end defun
1344
1345 @defun match-string-no-properties count &optional in-string
1346 This function is like @code{match-string} except that the result
1347 has no text properties.
1348 @end defun
1349
1350 @defun match-beginning count
1351 This function returns the position of the start of text matched by the
1352 last regular expression searched for, or a subexpression of it.
1353
1354 If @var{count} is zero, then the value is the position of the start of
1355 the entire match. Otherwise, @var{count} specifies a subexpression in
1356 the regular expression, and the value of the function is the starting
1357 position of the match for that subexpression.
1358
1359 The value is @code{nil} for a subexpression inside a @samp{\|}
1360 alternative that wasn't used or a repetition that repeated zero times.
1361 @end defun
1362
1363 @defun match-end count
1364 This function is like @code{match-beginning} except that it returns the
1365 position of the end of the match, rather than the position of the
1366 beginning.
1367 @end defun
1368
1369 Here is an example of using the match data, with a comment showing the
1370 positions within the text:
1371
1372 @example
1373 @group
1374 (string-match "\\(qu\\)\\(ick\\)"
1375 "The quick fox jumped quickly.")
1376 ;0123456789
1377 @result{} 4
1378 @end group
1379
1380 @group
1381 (match-string 0 "The quick fox jumped quickly.")
1382 @result{} "quick"
1383 (match-string 1 "The quick fox jumped quickly.")
1384 @result{} "qu"
1385 (match-string 2 "The quick fox jumped quickly.")
1386 @result{} "ick"
1387 @end group
1388
1389 @group
1390 (match-beginning 1) ; @r{The beginning of the match}
1391 @result{} 4 ; @r{with @samp{qu} is at index 4.}
1392 @end group
1393
1394 @group
1395 (match-beginning 2) ; @r{The beginning of the match}
1396 @result{} 6 ; @r{with @samp{ick} is at index 6.}
1397 @end group
1398
1399 @group
1400 (match-end 1) ; @r{The end of the match}
1401 @result{} 6 ; @r{with @samp{qu} is at index 6.}
1402
1403 (match-end 2) ; @r{The end of the match}
1404 @result{} 9 ; @r{with @samp{ick} is at index 9.}
1405 @end group
1406 @end example
1407
1408 Here is another example. Point is initially located at the beginning
1409 of the line. Searching moves point to between the space and the word
1410 @samp{in}. The beginning of the entire match is at the 9th character of
1411 the buffer (@samp{T}), and the beginning of the match for the first
1412 subexpression is at the 13th character (@samp{c}).
1413
1414 @example
1415 @group
1416 (list
1417 (re-search-forward "The \\(cat \\)")
1418 (match-beginning 0)
1419 (match-beginning 1))
1420 @result{} (17 9 13)
1421 @end group
1422
1423 @group
1424 ---------- Buffer: foo ----------
1425 I read "The cat @point{}in the hat comes back" twice.
1426 ^ ^
1427 9 13
1428 ---------- Buffer: foo ----------
1429 @end group
1430 @end example
1431
1432 @noindent
1433 (In this case, the index returned is a buffer position; the first
1434 character of the buffer counts as 1.)
1435
1436 @node Entire Match Data
1437 @subsection Accessing the Entire Match Data
1438
1439 The functions @code{match-data} and @code{set-match-data} read or
1440 write the entire match data, all at once.
1441
1442 @defun match-data &optional integers reuse reseat
1443 This function returns a list of positions (markers or integers) that
1444 record all the information on what text the last search matched.
1445 Element zero is the position of the beginning of the match for the
1446 whole expression; element one is the position of the end of the match
1447 for the expression. The next two elements are the positions of the
1448 beginning and end of the match for the first subexpression, and so on.
1449 In general, element
1450 @ifnottex
1451 number 2@var{n}
1452 @end ifnottex
1453 @tex
1454 number {\mathsurround=0pt $2n$}
1455 @end tex
1456 corresponds to @code{(match-beginning @var{n})}; and
1457 element
1458 @ifnottex
1459 number 2@var{n} + 1
1460 @end ifnottex
1461 @tex
1462 number {\mathsurround=0pt $2n+1$}
1463 @end tex
1464 corresponds to @code{(match-end @var{n})}.
1465
1466 Normally all the elements are markers or @code{nil}, but if
1467 @var{integers} is non-@code{nil}, that means to use integers instead
1468 of markers. (In that case, the buffer itself is appended as an
1469 additional element at the end of the list, to facilitate complete
1470 restoration of the match data.) If the last match was done on a
1471 string with @code{string-match}, then integers are always used,
1472 since markers can't point into a string.
1473
1474 If @var{reuse} is non-@code{nil}, it should be a list. In that case,
1475 @code{match-data} stores the match data in @var{reuse}. That is,
1476 @var{reuse} is destructively modified. @var{reuse} does not need to
1477 have the right length. If it is not long enough to contain the match
1478 data, it is extended. If it is too long, the length of @var{reuse}
1479 stays the same, but the elements that were not used are set to
1480 @code{nil}. The purpose of this feature is to reduce the need for
1481 garbage collection.
1482
1483 If @var{reseat} is non-@code{nil}, all markers on the @var{reuse} list
1484 are reseated to point to nowhere.
1485
1486 As always, there must be no possibility of intervening searches between
1487 the call to a search function and the call to @code{match-data} that is
1488 intended to access the match data for that search.
1489
1490 @example
1491 @group
1492 (match-data)
1493 @result{} (#<marker at 9 in foo>
1494 #<marker at 17 in foo>
1495 #<marker at 13 in foo>
1496 #<marker at 17 in foo>)
1497 @end group
1498 @end example
1499 @end defun
1500
1501 @defun set-match-data match-list &optional reseat
1502 This function sets the match data from the elements of @var{match-list},
1503 which should be a list that was the value of a previous call to
1504 @code{match-data}. (More precisely, anything that has the same format
1505 will work.)
1506
1507 If @var{match-list} refers to a buffer that doesn't exist, you don't get
1508 an error; that sets the match data in a meaningless but harmless way.
1509
1510 If @var{reseat} is non-@code{nil}, all markers on the @var{match-list} list
1511 are reseated to point to nowhere.
1512
1513 @findex store-match-data
1514 @code{store-match-data} is a semi-obsolete alias for @code{set-match-data}.
1515 @end defun
1516
1517 @node Saving Match Data
1518 @subsection Saving and Restoring the Match Data
1519
1520 When you call a function that may do a search, you may need to save
1521 and restore the match data around that call, if you want to preserve the
1522 match data from an earlier search for later use. Here is an example
1523 that shows the problem that arises if you fail to save the match data:
1524
1525 @example
1526 @group
1527 (re-search-forward "The \\(cat \\)")
1528 @result{} 48
1529 (foo) ; @r{Perhaps @code{foo} does}
1530 ; @r{more searching.}
1531 (match-end 0)
1532 @result{} 61 ; @r{Unexpected result---not 48!}
1533 @end group
1534 @end example
1535
1536 You can save and restore the match data with @code{save-match-data}:
1537
1538 @defmac save-match-data body@dots{}
1539 This macro executes @var{body}, saving and restoring the match
1540 data around it. The return value is the value of the last form in
1541 @var{body}.
1542 @end defmac
1543
1544 You could use @code{set-match-data} together with @code{match-data} to
1545 imitate the effect of the special form @code{save-match-data}. Here is
1546 how:
1547
1548 @example
1549 @group
1550 (let ((data (match-data)))
1551 (unwind-protect
1552 @dots{} ; @r{Ok to change the original match data.}
1553 (set-match-data data)))
1554 @end group
1555 @end example
1556
1557 Emacs automatically saves and restores the match data when it runs
1558 process filter functions (@pxref{Filter Functions}) and process
1559 sentinels (@pxref{Sentinels}).
1560
1561 @ignore
1562 Here is a function which restores the match data provided the buffer
1563 associated with it still exists.
1564
1565 @smallexample
1566 @group
1567 (defun restore-match-data (data)
1568 @c It is incorrect to split the first line of a doc string.
1569 @c If there's a problem here, it should be solved in some other way.
1570 "Restore the match data DATA unless the buffer is missing."
1571 (catch 'foo
1572 (let ((d data))
1573 @end group
1574 (while d
1575 (and (car d)
1576 (null (marker-buffer (car d)))
1577 @group
1578 ;; @file{match-data} @r{buffer is deleted.}
1579 (throw 'foo nil))
1580 (setq d (cdr d)))
1581 (set-match-data data))))
1582 @end group
1583 @end smallexample
1584 @end ignore
1585
1586 @node Search and Replace
1587 @section Search and Replace
1588 @cindex replacement after search
1589 @cindex searching and replacing
1590
1591 If you want to find all matches for a regexp in part of the buffer,
1592 and replace them, the best way is to write an explicit loop using
1593 @code{re-search-forward} and @code{replace-match}, like this:
1594
1595 @example
1596 (while (re-search-forward "foo[ \t]+bar" nil t)
1597 (replace-match "foobar"))
1598 @end example
1599
1600 @noindent
1601 @xref{Replacing Match,, Replacing the Text that Matched}, for a
1602 description of @code{replace-match}.
1603
1604 However, replacing matches in a string is more complex, especially
1605 if you want to do it efficiently. So Emacs provides a function to do
1606 this.
1607
1608 @defun replace-regexp-in-string regexp rep string &optional fixedcase literal subexp start
1609 This function copies @var{string} and searches it for matches for
1610 @var{regexp}, and replaces them with @var{rep}. It returns the
1611 modified copy. If @var{start} is non-@code{nil}, the search for
1612 matches starts at that index in @var{string}, so matches starting
1613 before that index are not changed.
1614
1615 This function uses @code{replace-match} to do the replacement, and it
1616 passes the optional arguments @var{fixedcase}, @var{literal} and
1617 @var{subexp} along to @code{replace-match}.
1618
1619 Instead of a string, @var{rep} can be a function. In that case,
1620 @code{replace-regexp-in-string} calls @var{rep} for each match,
1621 passing the text of the match as its sole argument. It collects the
1622 value @var{rep} returns and passes that to @code{replace-match} as the
1623 replacement string. The match-data at this point are the result
1624 of matching @var{regexp} against a substring of @var{string}.
1625 @end defun
1626
1627 If you want to write a command along the lines of @code{query-replace},
1628 you can use @code{perform-replace} to do the work.
1629
1630 @defun perform-replace from-string replacements query-flag regexp-flag delimited-flag &optional repeat-count map start end
1631 This function is the guts of @code{query-replace} and related
1632 commands. It searches for occurrences of @var{from-string} in the
1633 text between positions @var{start} and @var{end} and replaces some or
1634 all of them. If @var{start} is @code{nil} (or omitted), point is used
1635 instead, and the end of the buffer's accessible portion is used for
1636 @var{end}.
1637
1638 If @var{query-flag} is @code{nil}, it replaces all
1639 occurrences; otherwise, it asks the user what to do about each one.
1640
1641 If @var{regexp-flag} is non-@code{nil}, then @var{from-string} is
1642 considered a regular expression; otherwise, it must match literally. If
1643 @var{delimited-flag} is non-@code{nil}, then only replacements
1644 surrounded by word boundaries are considered.
1645
1646 The argument @var{replacements} specifies what to replace occurrences
1647 with. If it is a string, that string is used. It can also be a list of
1648 strings, to be used in cyclic order.
1649
1650 If @var{replacements} is a cons cell, @w{@code{(@var{function}
1651 . @var{data})}}, this means to call @var{function} after each match to
1652 get the replacement text. This function is called with two arguments:
1653 @var{data}, and the number of replacements already made.
1654
1655 If @var{repeat-count} is non-@code{nil}, it should be an integer. Then
1656 it specifies how many times to use each of the strings in the
1657 @var{replacements} list before advancing cyclically to the next one.
1658
1659 If @var{from-string} contains upper-case letters, then
1660 @code{perform-replace} binds @code{case-fold-search} to @code{nil}, and
1661 it uses the @code{replacements} without altering the case of them.
1662
1663 Normally, the keymap @code{query-replace-map} defines the possible
1664 user responses for queries. The argument @var{map}, if
1665 non-@code{nil}, specifies a keymap to use instead of
1666 @code{query-replace-map}.
1667
1668 This function uses one of two functions to search for the next
1669 occurrence of @var{from-string}. These functions are specified by the
1670 values of two variables: @code{replace-re-search-function} and
1671 @code{replace-search-function}. The former is called when the
1672 argument @var{regexp-flag} is non-@code{nil}, the latter when it is
1673 @code{nil}.
1674 @end defun
1675
1676 @defvar query-replace-map
1677 This variable holds a special keymap that defines the valid user
1678 responses for @code{perform-replace} and the commands that use it, as
1679 well as @code{y-or-n-p} and @code{map-y-or-n-p}. This map is unusual
1680 in two ways:
1681
1682 @itemize @bullet
1683 @item
1684 The ``key bindings'' are not commands, just symbols that are meaningful
1685 to the functions that use this map.
1686
1687 @item
1688 Prefix keys are not supported; each key binding must be for a
1689 single-event key sequence. This is because the functions don't use
1690 @code{read-key-sequence} to get the input; instead, they read a single
1691 event and look it up ``by hand.''
1692 @end itemize
1693 @end defvar
1694
1695 Here are the meaningful ``bindings'' for @code{query-replace-map}.
1696 Several of them are meaningful only for @code{query-replace} and
1697 friends.
1698
1699 @table @code
1700 @item act
1701 Do take the action being considered---in other words, ``yes.''
1702
1703 @item skip
1704 Do not take action for this question---in other words, ``no.''
1705
1706 @item exit
1707 Answer this question ``no,'' and give up on the entire series of
1708 questions, assuming that the answers will be ``no.''
1709
1710 @item act-and-exit
1711 Answer this question ``yes,'' and give up on the entire series of
1712 questions, assuming that subsequent answers will be ``no.''
1713
1714 @item act-and-show
1715 Answer this question ``yes,'' but show the results---don't advance yet
1716 to the next question.
1717
1718 @item automatic
1719 Answer this question and all subsequent questions in the series with
1720 ``yes,'' without further user interaction.
1721
1722 @item backup
1723 Move back to the previous place that a question was asked about.
1724
1725 @item edit
1726 Enter a recursive edit to deal with this question---instead of any
1727 other action that would normally be taken.
1728
1729 @item delete-and-edit
1730 Delete the text being considered, then enter a recursive edit to replace
1731 it.
1732
1733 @item recenter
1734 Redisplay and center the window, then ask the same question again.
1735
1736 @item quit
1737 Perform a quit right away. Only @code{y-or-n-p} and related functions
1738 use this answer.
1739
1740 @item help
1741 Display some help, then ask again.
1742 @end table
1743
1744 @defvar multi-query-replace-map
1745 This variable holds a keymap that extends @code{query-replace-map} by
1746 providing additional keybindings that are useful in multi-buffer
1747 replacements.
1748 @end defvar
1749
1750 @defvar replace-search-function
1751 This variable specifies a function that @code{perform-replace} calls
1752 to search for the next string to replace. Its default value is
1753 @code{search-forward}. Any other value should name a function of 3
1754 arguments: the first 3 arguments of @code{search-forward}
1755 (@pxref{String Search}).
1756 @end defvar
1757
1758 @defvar replace-re-search-function
1759 This variable specifies a function that @code{perform-replace} calls
1760 to search for the next regexp to replace. Its default value is
1761 @code{re-search-forward}. Any other value should name a function of 3
1762 arguments: the first 3 arguments of @code{re-search-forward}
1763 (@pxref{Regexp Search}).
1764 @end defvar
1765
1766 @node Standard Regexps
1767 @section Standard Regular Expressions Used in Editing
1768 @cindex regexps used standardly in editing
1769 @cindex standard regexps used in editing
1770
1771 This section describes some variables that hold regular expressions
1772 used for certain purposes in editing:
1773
1774 @defopt page-delimiter
1775 This is the regular expression describing line-beginnings that separate
1776 pages. The default value is @code{"^\014"} (i.e., @code{"^^L"} or
1777 @code{"^\C-l"}); this matches a line that starts with a formfeed
1778 character.
1779 @end defopt
1780
1781 The following two regular expressions should @emph{not} assume the
1782 match always starts at the beginning of a line; they should not use
1783 @samp{^} to anchor the match. Most often, the paragraph commands do
1784 check for a match only at the beginning of a line, which means that
1785 @samp{^} would be superfluous. When there is a nonzero left margin,
1786 they accept matches that start after the left margin. In that case, a
1787 @samp{^} would be incorrect. However, a @samp{^} is harmless in modes
1788 where a left margin is never used.
1789
1790 @defopt paragraph-separate
1791 This is the regular expression for recognizing the beginning of a line
1792 that separates paragraphs. (If you change this, you may have to
1793 change @code{paragraph-start} also.) The default value is
1794 @w{@code{"[@ \t\f]*$"}}, which matches a line that consists entirely of
1795 spaces, tabs, and form feeds (after its left margin).
1796 @end defopt
1797
1798 @defopt paragraph-start
1799 This is the regular expression for recognizing the beginning of a line
1800 that starts @emph{or} separates paragraphs. The default value is
1801 @w{@code{"\f\\|[ \t]*$"}}, which matches a line containing only
1802 whitespace or starting with a form feed (after its left margin).
1803 @end defopt
1804
1805 @defopt sentence-end
1806 If non-@code{nil}, the value should be a regular expression describing
1807 the end of a sentence, including the whitespace following the
1808 sentence. (All paragraph boundaries also end sentences, regardless.)
1809
1810 If the value is @code{nil}, the default, then the function
1811 @code{sentence-end} has to construct the regexp. That is why you
1812 should always call the function @code{sentence-end} to obtain the
1813 regexp to be used to recognize the end of a sentence.
1814 @end defopt
1815
1816 @defun sentence-end
1817 This function returns the value of the variable @code{sentence-end},
1818 if non-@code{nil}. Otherwise it returns a default value based on the
1819 values of the variables @code{sentence-end-double-space}
1820 (@pxref{Definition of sentence-end-double-space}),
1821 @code{sentence-end-without-period} and
1822 @code{sentence-end-without-space}.
1823 @end defun