使用emacs,如何在缓冲区中搜索和替换正则表达式?除了以交互方式评估elisp之外,我如何以编程方式执行此操作?例如,使用制表符替换一个或多个空格,我需要将' +'
(一个或多个空格)与C-q-TAB
匹配。这可能吗?
答案 0 :(得分:3)
我相信答案是M-x replace-regexp
答案 1 :(得分:3)
以编程方式,您可以按照以下方式执行此操作:
(defun region-replace-multiple-spaces-with-single-space(beg end)
(interactive "*r")
(save-restriction
(narrow-to-region beg end)
(save-excursion
(goto-char (point-min))
(while (search-forward-regexp " +" nil t)
(replace-match " " nil nil)))))
答案 2 :(得分:1)
我有一个多用途的replace-regexp
:
query-replace-regexp
以下是代码:
(global-set-key (kbd "C-/") 'replace-regexp-dwim)
(defun replace-regexp-dwim (arg)
(interactive "P")
(destructuring-bind (from to &rest)
(query-replace-read-args "Replace regexp" nil)
(if arg
(query-replace-regexp from to)
(let ((st (if (region-active-p)
(region-beginning)
(line-beginning-position)))
(en (if (region-active-p)
(region-end)
(line-end-position))))
(goto-char st)
(while (re-search-forward from en t)
(replace-match to nil t))))))