This function replaces all or part of the text matched by the last search. It works by means of the match data.
This function performs a replacement operation on a buffer or string.
The String to replace the matched text
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.
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.
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;
error
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.
If SUBEXP is non-‘nil’, that says to replace just subexpression number SUBEXP of the regexp that was matched, not the entire match.
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
.