是否有一個本地Emacs Lisp函數,其行爲如同strpos()
in PHP?它應該返回當前緩衝區中給定字符串第一次出現的位置。函數search-forward
很好,但它修改了字符位置。Emacs Lisp中的strpos
2
A
回答
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
。
5
對應於PHP strpos
,要搜索某個字符串在另一字符串的函數,是從cl
包search
:
(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)))
...)))
相關問題
- 1. Emacs Lisp中的PPRINT?
- 2. 讓和FLET中的Emacs Lisp
- 3. 的Emacs Lisp問題
- 4. Emacs lisp char-table
- 5. strtotime for Emacs Lisp
- 6. common lisp和emacs
- 7. strstr()in emacs lisp?
- 8. 在Emacs Lisp中解析
- 9. Emacs Lisp的方案方言
- 10. Lisp的Emacs配置腳本
- 11. 的Emacs Lisp:從路徑
- 12. 的Emacs Lisp搜索落後
- 13. 如何擺脫Emacs Lisp中的maphash?
- 14. 獲取Emacs Lisp中的VC根目錄
- 15. 獲取Emacs Lisp中的當前目錄
- 16. Emacs Lisp中的替換字符?
- 17. 參數中的空格字符(emacs lisp)
- 18. Emacs Lisp宏步進器
- 19. Emacs Lisp - 打開新窗口
- 20. Emacs lisp代碼縮進
- 21. Emacs Lisp:嵌套在ibuffer中超過`max-lisp-eval-depth'
- 22. 在Lisp(Clojure,Emacs Lisp)中,list和quote有什麼區別?
- 23. #[...]在emacs-lisp中意味着什麼?
- 24. 在emacs lisp中包裝一個函數
- 25. 在Emacs Lisp函數中分割窗口
- 26. 在Emacs Lisp中正確使用apply?
- 27. 在Emacs Lisp中創建Windows路徑
- 28. 在emacs lisp中使用側滑手勢
- 29. Emacs Lisp:在alist中評估變量
- 30. 如何在Emacs Lisp中連接模式?
''(buffer-string)'製作緩衝區內容的副本,所以對於大型緩衝區來說是不實用的。 – Gilles 2010-10-09 19:29:48
@Gilles - 非常真實的,我會添加一個說明,我應該原本。謝謝。 – 2010-10-09 19:59:12
我就像你的代碼一樣來到了解決方案。謝謝。 – 2010-10-10 17:59:45