Emacs: Using Interactive Regex Features in Elisp (Pseudo-call)
Emacs users frequently utilize powerful interactive replacement commands such as replace-regexp and query-replace-regexp. Beyond basic text replacement and capture group back-references (like \& and \1 ), interactive replacement supports two lesser-known but highly powerful special sequences:
\,(...): Allows the execution of arbitrary Elisp expressions within the replacement string, inserting the result.\#: Represents the replacement counter (current iteration), starting from 0.
However, these convenient features are typically unavailable when invoking replacement functions via non-interactive code in Elisp programming.
: In a reply, user @Kana pointed out that the same effect can be achieved directly using the following function, which even supports the \,(...) format:
(defun my/replace-regexp (regexp replacement)
"`replace-regexp', non-interactively."
(perform-replace
regexp
(query-replace-compile-replacement replacement t)
nil t nil))
Tested and confirmed to work as expected.