2010-10-09 89 views

回答

3

你可以這樣做:

;; does not modify match-data 
(string-match-p (regexp-quote "string") (buffer-string)) 

;; does modify match-data 
(string-match (regexp-quote "string") (buffer-string)) 

但這些呼叫使字符串,這是不實際的副本。更好的解決方案是使用這個:

(defun my-strpos (string) 
    "mimic strpos" 
    (save-excursion 
    (save-match-data 
     (goto-char (point-min))    ; or not 
     (when (search-forward string nil t) 
     (match-beginning 0))))) 

它也取決於你想要做什麼後,找到位置。 match data的文檔可能會有用。如果要使用match-data後綴,請將呼叫移除至'save-match-data

+1

''(buffer-string)'製作緩衝區內容的副本,所以對於大型緩衝區來說是不實用的。 – Gilles 2010-10-09 19:29:48

+0

@Gilles - 非常真實的,我會添加一個說明,我應該原本。謝謝。 – 2010-10-09 19:59:12

+0

我就像你的代碼一樣來到了解決方案。謝謝。 – 2010-10-10 17:59:45

5

對應於PHP strpos,要搜索某個字符串在另一字符串的函數,是從clsearch

(require 'cl) 
(search needle haystack :start2 offset) 

如果你要搜索一個緩衝區內的字符串,使用search-forward。由於這會更改當前緩衝區和該緩衝區內的點,因此需要將函數包裝在save-excursion中;這是一個常見的Emacs Lisp習慣用法。您還應該在save-match-data中包裝您的功能,以免干擾您的代碼的任何調用的搜索。

(save-match-data 
    (save-excursion 
    (set-buffer haystack) 
    (goto-char (or offset (point-min))) 
    (let ((pos (search-forward needle nil t))) 
     ...)))