3

Emacs Lisp has regexp-quote to quote any string to match it literally. Apparently, there is no equivalent function to quote an arbitrary replacement string to use it literally. I mean, what could I use instead of the imaginary regexp-quote-replacement in the following contrived[1] code?

(replace-regexp (regexp-quote "^$") (regexp-quote-replacement "\\&\\?"))

This code would be meant to replace a literal ^$ with a literal \&\?.

--

[1] I know that I could use replace-string in this case to achieve the same result.

6

Use a search and replace loop instead.

As the doc of replace-regexp indicates:

This function is for interactive use only;
in Lisp code use re-search-forward and replace-match instead.

One of the advantages of this approach is that replace-match has a LITERAL argument, which does what you're asking for.

(while (search-forward-regexp SOME-RX nil 'noerror)
  ;; This \\1 will be inserted literally as \1
  (replace-match " \\1" nil 'literal))
  • The question as posed says nothing about not wanting to use the function interactively. This does not really answer the question posed about replace-regexp at all. – Drew Dec 2 '14 at 2:55
  • @Drew (1) The question asks for something analogous to regexp-quote but which can be used for replacements. regexp-quote cannot be used interactively. (2) The example provided was not an interactive call, it was a piece of elisp code. (3) Given (1) and (2), it seems safer to assume the objective is elisp code. I'll be happy to retract if the author says otherwise. – Malabarba Dec 2 '14 at 3:18
  • I guess you're right. Funny that the OP was able to discover regexp-quote and learn about constructs such as \& in the TO-STRING, but apparently never noticed the several notes about the function not being intended for interactive use (the manual is even clearer about that than the doc string). – Drew Dec 2 '14 at 6:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.