regex - 在 lisp 中使用替换正则表达式的问题

标签 regex emacs elisp

在我的文件中,我有很多 ID="XXX"的实例,我想用 ID="0"替换第一个实例,用 ID="1"替换第二个实例,依此类推。

当我以交互方式使用 regexp-replace 时,我使用 ID="[^"]*" 作为搜索字符串,并使用 ID="\#" 作为替换字符串,一切正常。

现在我想将它绑定(bind)到一个键上,所以我尝试在 lisp 中这样做,如下所示:

(replace-regexp "ID=\"[^\"]*\"" "ID=\"\\#\"")

但是当我尝试评估它时,我得到一个“选择删除的缓冲区”错误。这可能与转义字符有关,但我无法弄清楚。

最佳答案

不幸的是,\# 构造仅在对 replace-regexp 的交互式调用中可用。来自 documentation :

In interactive calls, the replacement text may contain `\,'
followed by a Lisp expression used as part of the replacement
text.  Inside of that expression, `\&' is a string denoting the
whole match, `\N' a partial match, `\#&' and `\#N' the respective
numeric values from `string-to-number', and `\#' itself for
`replace-count', the number of replacements occurred so far.

在文档的末尾,您会看到以下提示:

This function is usually the wrong thing to use in a Lisp program.
What you probably want is a loop like this:
  (while (re-search-forward REGEXP nil t)
    (replace-match TO-STRING nil nil))
which will run faster and will not set the mark or print anything.

这将我们引向这段省略号:

(save-excursion
  (goto-char (point-min))
  (let ((count 0))
    (while (re-search-forward "ID=\"[^\"]*\"" nil t)
      (replace-match (format "ID=\"%s\"" (setq count (1+ count)))))))

您也可以使用键盘 macro ,但我更喜欢 lisp 解决方案。

关于regex - 在 lisp 中使用替换正则表达式的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6146124/

相关文章:

javascript - 大括号上的 JS 正则表达式

emacs - Emacs Lisp 中 apply 的正确用法?

c++ - 将 C++ 片段添加到 Jetbrains Clion

lisp - Emacs 口齿不清 : why does this sexp cause an invalid-function error?

emacs - 为什么 add-hook 允许 `hook' 无效?

javascript - 删除句点后的空格 javascript

javascript - 如果指定了多个分隔符,javascript 的 split 函数如何通过分隔符工作

emacs - 如何向 emacs 宏添加动态触摸和/或查询替换?

java - 使用 Regex Java 进行密码验证

Emacs:同一文件的多个 View