在我的文件中,我有很多ID ="XXX"的实例,我想用ID ="0"替换第一个,ID ="1"的第二个,依此类推.
当我以交互方式使用regexp-replace时,我使用ID="[^"]*"搜索字符串ID="\#"作为替换字符串,一切都很好.
现在我想将它绑定到一个键,所以我试着在lisp中这样做,就像这样:
(replace-regexp "ID=\"[^\"]*\"" "ID=\"\\#\"")
Run Code Online (Sandbox Code Playgroud)
但是当我尝试评估它时,我得到一个"选择已删除的缓冲区"错误.这可能与转义字符有关,但我无法弄明白.
不幸的是,该\#构造仅在交互式调用中可用replace-regexp.从文档:
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.
Run Code Online (Sandbox Code Playgroud)
在文档的最后,您将看到此提示:
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.
Run Code Online (Sandbox Code Playgroud)
然后,我们引导我们到这个elisp:
(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)))))))
Run Code Online (Sandbox Code Playgroud)
你也可以使用键盘宏,但我更喜欢lisp解决方案.
| 归档时间: |
|
| 查看次数: |
568 次 |
| 最近记录: |