Some time ago @Oleg Pavliv explained in https://unix.stackexchange.com/questions/47615/emacs-simple-arithmetics-in-query-replace how to do simple arithmetics in query replace (interactively) in emacs.
Now I want to use the same method for a small elisp program but it doesn’t work. Consider for example the following minimal example of elisp code:
(defun Nshift ()
(interactive)
(query-replace-regexp "\\([0-9]+\\)\\.Number" "\\,((+ 3 \\#1)).Number")
)
Now suppose I run Nshift in a buffer which contains for example the string 4.Number then I get the following error message.
match-substitute-replacement: Invalid use of `\' in replacement text
How would a correct elisp implementation of Nshift look like?
Edit:
I don’t see how Seans answer generalizes with easy and readable syntax to more complicated replacements (which I need in my application), so for example what would be the correct (and easy to read) equivalent to
(query-replace-regexp "\\([0-9]+\\)\\.Number.\\([0-9]+\\)" "\\,((+ 3 \\#1)).Number.\\,((+ 8 \\#2))")
Like this:
EDITED TO ADD:
Your expanded example could be implemented in this way:
It’s actually even easier than my original solution, because I forgot that
replace-matchhas an optional fifth argument that causes it to replace just a single subexpression, and saves you from having to duplicate the fixed text (“.Number.”) in the replacement text.There’s some refactoring that could be done here:
Then Nshift could be implemented like so: