2010-07-19 18 views
36

我一直在emacs lisp文檔中隨處搜索正則表達式如何搜索字符串。我找到的是如何在緩衝區中執行此操作。elisp正則表達式在字符串中搜索,而不是緩衝區

有什麼我失蹤了嗎?我應該將我的字符串吐在臨時緩衝區中並在那裏搜索它嗎?這只是elisp的編碼風格,我會習慣嗎?有沒有解決這個問題的標準解決方案。當我能夠直接搜索已經存在的變量時,操作緩衝區似乎很有用。

回答

25

Here is a discussion of string content vs buffer content in the Emacs wiki.只需將您的字符串存儲爲變量。

棘手的事情about strings是你通常不會修改字符串本身(除非你在字符串上執行數組函數,因爲字符串是一個數組,但通常應該避免),但是你返回修改過的字符串。

無論如何,這裏是一個在elisp中使用字符串的例子。

這將從一個字符串的結尾修剪空白:

(setq test-str "abcdefg ") 
(when (string-match "[ \t]*$" test-str) 
    (message (concat "[" (replace-match "" nil nil test-str) "]"))) 
11

你要找的功能是string-match。如果您需要重複執行匹配,請將其返回的索引用作下一次調用的可選「開始」參數。該文檔位於ELisp手冊的「正則表達式搜索」一章中。

3

要替換字符串中的每個正則表達式匹配,請查看replace-regexp-in-string

1

要搜索的字符串

(defun string-starts-with-p (string prefix) 
    "Return t if STRING starts with PREFIX." 
    (and 
    (string-match (rx-to-string `(: bos ,prefix) t) 
        string) 
    t)) 

的開始搜索字符串的結尾

(defun string-ends-with-p (string suffix) 
    "Return t if STRING ends with SUFFIX." 
    (and (string-match (rx-to-string `(: ,suffix eos) t) 
        string) 
     t)) 
相關問題