Emacs:正则表达式替换为更改大小写(在脚本中)

Mat*_*boz 5 regex emacs replace

这与Emacs有关 :正则表达式替换为更改大小写

我的另一个问题是我需要编写搜索替换脚本,但"\,()"只有在交互使用时,解决方案才适用(对我而言)(emacs 24.2.1).在脚本内部,它给出错误:" \'替换文本中的无效使用".

我通常会在某些文件中写一个"执行替换",以便在需要时加载.类似于:(

执行 - 替换"<\\([^>]+\\)>" "<\\,(downcase \1)>"tt nil 1 nil(point-min)(point-max))

应该可以调用一个函数来生成替换(pg 741 of the emacs lisp manual),但我尝试了以下的许多变体而没有运气:

(defun myfun ()
    (downcase (match-string 0)))

(perform-replace "..." (myfun . ()) t t nil)
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

ffe*_*tte 3

像这样的构造\,()只允许在交互式调用中使用query-replace,这就是 Emacs 在您的情况下抱怨的原因。

的文档perform-replace提到你不应该在 elisp 代码中使用它,并提出了一个更好的替代方案,我们可以在此基础上构建以下代码:

(while (re-search-forward "<\\([^>]+\\)>" nil t)
  (replace-match (downcase (match-string 0)) t nil))
Run Code Online (Sandbox Code Playgroud)

如果您仍然想以交互方式向用户查询有关替换的信息,那么perform-replace像您一样使用可能是正确的做法。您的代码中存在一些不同的问题:

  1. 正如elisp 手册中所述,替换函数必须采用两个参数(您在 cons 单元中提供的数据和已进行的替换数)。

  2. 正如 的文档query-replace-regexp(或elisp 手册)中所述,您需要确保case-fold-searchorcase-replace设置为 nil,以便案例模式不会转移到替换中。

  3. 您需要引用 cons cell (myfun . nil),否则它将被解释为函数调用并过早评估。

这是一个工作版本:

(while (re-search-forward "<\\([^>]+\\)>" nil t)
  (replace-match (downcase (match-string 0)) t nil))
Run Code Online (Sandbox Code Playgroud)