在文本缓冲区中,我想检查文件是否以字符串" abc
"结尾?只跟零到两个换行符(然后删除这个结束字符)。
所以我需要像looking-at-backwards
这样的东西,或者我想在文件末尾匹配(不是行尾)。什么是实现这一目标的简单方法?
答案 0 :(得分:4)
looking-back
是您正在寻找的向后匹配的功能
使用常规postifx运算符 \{m,n\}最多可匹配2个换行符:
(save-excursion
(goto-char (point-max))
(when (looking-back "^abc\n\\{,2\\}")
(delete-region (match-beginning 0) (match-end 0))))
答案 1 :(得分:0)
您所描述的内容并未要求在Emacs中通常称为正则表达式搜索。它要求在缓冲区末尾(eob)匹配正则表达式。我已经相应地编辑了你的问题标题和文字。
为此,您只需暂时移动到缓冲区的末尾,并使用looking-back
检查正则表达式匹配。
(defun delete-abc-SPC-<-3-newlines ()
"Delete `abc ' followed by up to 2 newlines at eob."
(interactive)
(let ((ends-w-<-3-newlines nil))
(save-excursion
(goto-char (point-max))
(setq ends-w-<-3-newlines (looking-back "abc \n?\n?\n?")))
(when ends-w-<-3-newlines
(delete-region (match-beginning 0) (match-end 0)))))
如果您不想将缓冲区视为新修改的,请使用:
(defun delete-abc-SPC-<-3-newlines ()
"Delete `abc ' followed by up to 2 newlines at eob."
(interactive)
(let ((ends-w-<-3-newlines nil)
(mod-buf (buffer-modified-p)))
(save-excursion
(goto-char (point-max))
(setq ends-w-<-3-newlines (looking-back "abc \n?\n?\n?")))
(when ends-w-<-3-newlines
(delete-region (match-beginning 0) (match-end 0)))
(set-buffer-modified-p mod-buf)))