用于在Emacs中进行文本搜索的AND运算符

时间:2017-04-07 03:58:23

标签: regex emacs

我是Emacs的新手。我可以使用&#34来搜索文本并在单独的缓冲区中显示所有行; M-x出现"。我还可以使用OR运算符搜索多个文本项:one \ | two,它将找到带有"一个"或者"两个" (如Emacs occur mode search for multiple strings所述)。如何使用" one"和"两个"?我尝试过使用\&和\&&但他们不起作用。我需要为此创建一个宏或函数吗?

编辑:

我尝试在Racket中编写上面的函数(Scheme衍生物)。以下作品:

#lang racket

(define text '("this is line number one"
               "this line contains two keyword"
               "this line has both one and two keywords"
               "this line contains neither"
               "another two & one words line"))

(define (srch . lst)    ; takes variable number of arguments
  (for ((i lst))
    (set! text (filter (λ (x) (string-contains? x i)) text)))
  text)

(srch "one" "two")

输出:

'("this line has both one and two keywords" "another two & one words line")

但我怎么能把它放在Emacs Lisp中?

1 个答案:

答案 0 :(得分:2)

Regex不支持"和"因为当你尝试在任何非平凡的正则表达式中使用它时,它的用处和奇怪的语义非常有限。通常的解决方法是只搜索one.*two\|two.*one ...或者在*Occur*的情况下,可能只搜索one然后搜索M-x delete-non-matching-lines two

(你必须先将*Occur*缓冲区标记为可写。read-only-mode是一个切换;默认的键绑定是C-x C-q。至少在我的Emacs中,你有将光标移离第一行,或者你得到"文本是只读的#34;。)

(defun occur2 (regex1 regex2)
  "Search for lines matching both REGEX1 and REGEX2 by way of `occur'.
We first (occur regex1) and then do (delete-non-matching-lines regex2) in the
*Occur* buffer."
  (interactive "sFirst term: \nsSecond term: ")
  (occur regex1)
  (save-excursion
    (other-window 1)
    (let ((buffer-read-only nil))
      (forward-line 1)
      (delete-non-matching-lines regex2))))

save-excursionother-window有点像疣,但它似乎比硬编码*Occur*缓冲区的名称更容易(它永远不会是真的;你可以有几个出现缓冲区)或切换到那里只是为了获取缓冲区名称,然后使用set-buffer等做正确的事。