Problem using replace-regexp in lisp

in my file, I have many instances of ID = "XXX" and I want to replace the first with ID = "0", the second with ID = "1", etc.

When I use regexp-replace interactively, I use ID="[^"]*"as a search string and ID="\#"as a replacement string, and all is well.

now I want to bind this to a key, so I tried to do this in lisp, for example:

(replace-regexp "ID=\"[^\"]*\"" "ID=\"\\#\"")

but when I try to evaluate it, I get a "remote buffer selection" error. This is probably something related to escape characters, but I can't figure it out.

+3
source share
1 answer

Unfortunately, the constructor \#is only available in an interactive call replace-regexp. From the doc:

In interactive calls, the replacement text may contain `\,'
followed by a Lisp expression used as part of the replacement
text.  Inside of that expression, `\&' is a string denoting the
whole match, `\N' a partial match, `\#&' and `\#N' the respective
numeric values from `string-to-number', and `\#' itself for
`replace-count', the number of replacements occurred so far.

:

This function is usually the wrong thing to use in a Lisp program.
What you probably want is a loop like this:
  (while (re-search-forward REGEXP nil t)
    (replace-match TO-STRING nil nil))
which will run faster and will not set the mark or print anything.

elisp:

(save-excursion
  (goto-char (point-min))
  (let ((count 0))
    (while (re-search-forward "ID=\"[^\"]*\"" nil t)
      (replace-match (format "ID=\"%s\"" (setq count (1+ count)))))))

macro, lisp.

+7

All Articles