首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在lisp中使用replace-regexp的问题

在lisp中使用replace-regexp的问题
EN

Stack Overflow用户
提问于 2011-05-27 07:07:50
回答 1查看 692关注 0票数 3

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

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

现在我想把它绑定到一个密钥上,所以我试着用lisp来实现,如下所示:

代码语言:javascript
复制
(replace-regexp "ID=\"[^\"]*\"" "ID=\"\\#\"")

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-05-27 07:32:51

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

代码语言:javascript
复制
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.

在文档的末尾,您将看到这样的提示:

代码语言:javascript
复制
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.

这就引出了下面这段elisp:

代码语言:javascript
复制
(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解决方案。

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6146124

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档