It seems that
replace-regexp has a different behavior if called interactively and not, but I do not understand why, and how to get the wanted behavior.
What I want is the non-interactive equivalent of:
M-x replace-regexp RET foo1 RET foo\#
which, if called on buffer
foo1 foo1 foo1
foo0 foo1 foo2
Now, non-interactively, the naive
(replace-regexp "foo1" "foo\\#")
"Invalid use of '\' in replacement text"
The same happens with
(funcall-interactive "foo1" "foo\\#")
And singling or doubling the backslashes give the expected (unwanted) results:
(replace-regexp "foo1" "foo\#") ;; foo# ;; foo# ;; foo# (replace-regexp "foo1" "foo\\\\#") ;; foo\# ;; foo\# ;; foo\#
Of course, running
call-interactively works, but in my use-case the regexp and replacement string will be crafted by elisp code.
Running a loop searching and replacing would probably work, but is it really the only solution? It seems hard to believe.