UP | HOME

▼ 本文更新于 [2025-11-21 五 23:04]

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:

  1. \,(...) : Allows the execution of arbitrary Elisp expressions within the replacement string, inserting the result.
  2. \# : 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.

© Published by Emacs 31.0.50 (Org mode 9.8-pre) | RSS English-Index