Next: , Up: Replacing Text Using Match Data   [Index]


8.4.4.1 replace-match

This function replaces all or part of the text matched by the last search. It works by means of the match data.

Function: replace-match replacement &optional fixedcase literal string subexp

This function performs a replacement operation on a buffer or string.

REPLACEMENT

The String to replace the matched text

FIXEDCASE

If FIXEDCASE is non-‘nil’, then replace-match uses the replacement text without case conversion; otherwise, it converts the replacement text depending upon the capitalization of the text to be replaced.

LITERAL

If LITERAL is non-‘nil’, then REPLACEMENT is inserted exactly as it is, the only alterations being case changes as needed. If it is ‘nil’ (the default), then the character ‘\’ is treated specially.

If a ‘\’ appears in REPLACEMENT, then it must be part of one of the following sequences:

\&

This stands for the entire text being replaced.

\N

where N is a digit; this stands for the text that matched the Nth subexpression in the original regexp.

\\

This stands for a single ‘\’ in the replacement text.

\?

This stands for itself (for compatibility with ‘replace-regexp’ and related commands;

any other

error

STRING

If you performed the last search on a string, pass the same string as STRING. Then this function returns a new string, in which the matched text is replaced by REPLACEMENT.

SUBEXP

If SUBEXP is non-‘nil’, that says to replace just subexpression number SUBEXP of the regexp that was matched, not the entire match.

Replace All Matches in Part of a Buffer

If you want to find all matches for a regexp in part of the buffer, and replace them, the best way is to write an explicit loop using re-search-forward and replace-match, like this:

(while (re-search-forward "foo[ \t]+bar" nil t)
  (replace-match "foobar"))

Replacing matches in a string is more complex, especially if you want to do it efficiently. So Emacs provides a function to do this: replace-regexp-in-string.


Next: match-substitue-replacement, Up: Replacing Text Using Match Data   [Index]