2015-02-11 30 views
-1

我有一個文件格式爲在emacs中轉換字符串和grep的lisp?

abc|<hoge> 
a|<foo> b|<foo> c|<foo> 
family|<bar> guy|<bar> 
a|<foo> comedy|<bar> show|<foo> 
action|<hoge> 

,並想生對emacs的搜索搜索字符串(如「喜劇表演」,而不是a|<foo> comedy|<bar> show|<foo>)。

我相信在lisp上使用grep會是最簡單的答案,但我還沒有想出如何。有人會啓發我嗎?

+0

''喜劇節目''是**不是**正則表達式將匹配'a | 喜劇| 顯示| '實用程序grep包含'E'的可選參數,它代表擴展的正則表達式。您的問題有點不清楚,但似乎在問如何使用grep來搜索正則表達式,以及如何使用Emacs爲外部實用程序grep提供的前端執行相同的搜索。您可能希望進一步澄清問題,甚至包含grep標記,因爲您可能會問如何使用該實用程序執行特定的搜索。 – lawlist 2015-02-11 22:51:40

+0

user2283547:你想在Emacs中進行交互式搜索嗎?或者你想查看所有匹配結果的列表? – phils 2015-02-11 22:54:49

回答

1

那麼,grep是一個單獨的程序(你也可以使用)。在Emacs中,您可以使用功能search-forward-regexp,您可以使用M-x(保存Meta,通常爲Alt密鑰,然後按x)運行,然後鍵入search-forward-regexp並按Return運行。

然後您需要鍵入正則表達式來搜索。簡單地說,好像你要忽略|<東西>,這在Emacs的各種正則表達式是:

|<[a-z]+> 

,所以你可以搜索例如

a|<[a-z]+> comedy|<[a-z]+> show|<[a-z]+> 

您可以創建一個Lisp函數將字符串這種方式進行轉換,通過拆分它的空間並添加正則表達式序列:

(defun find-string-in-funny-file (s)      ; Define a function 
    "Find a string in the file with the |<foo> things in it." ; Document its purpose 
    (interactive "sString to find: ")       ; Accept input if invoked interactively with M-x 
    (push-mark)            ; Save the current location, so `pop-global-mark' can return here 
                  ; (usually C-u C-SPC) 
    (goto-char 0)            ; Start at the top of the file 
    (let ((re (apply #'concat         ; join into one string… 
        (cl-loop 
        for word in (split-string s " ")  ; for each word in `s' 
        collect (regexp-quote word)    ; collect that word, plus 
        collect "|<[a-z]+> "))))    ; also the regex bits to skip 
    (search-forward-regexp         ; search for the next occurrence 
    (substring re 0 (- (length re) 2)))))     ; after removing the final space from `re' 

您可以探索了每個那些功能,在做(在線)Emacs Lisp手冊;例如,從菜單中選擇「幫助→描述→功能」或按C-h f(控制+ h,然後f)並鍵入interactive(RET)以獲取該特殊表格的手冊文檔。

如果粘貼上述(defun)*scratch*緩衝,並在年底的最後)後,將光標定位,您可以按C-j對其進行評估,該函數將保持與你,直到你關閉的Emacs。

如果您將它保存在名爲東西.el,您可以使用M-xload-file在未來再次裝入文件。

如果您然後加載您的「有趣」文件,並輸入M-xfind-string-in-funny-file,它會在您的文件中搜索您的字符串,並將光標留在該字符串上。如果找不到,您會看到一條消息。

BUGS:功能不如壯觀

+1

您可以使用'regexp-quote'來處理這些單詞,以防止無意中使用正則表達式特殊字符。 – phils 2015-02-12 02:04:39

+0

謝謝,我知道它存在。我會補丁上面。 – BRFennPocock 2015-02-12 04:03:51