簡體   English   中英

Emacs lisp逃避正則表達式

[英]Emacs lisp escaping regexp

作為為emacs定義函數的第一次經驗,我想編寫一個函數來獲取argv [某個數字]的所有出現並按順序重新編號。

這是在emacs內部使用replace-regexp完成的,輸入為搜索/替換字符串

argv\[\([0-9]+\)\]
argv[\,(+ 1 \#)]

現在,我想在我的.emacs中寫這個,所以我理解我還需要逃避Lisp特殊字符。 所以在我看來它應該寫

(defun argv-order () 
  (interactive)
  (goto-char 1)
  (replace-regexp "argv\\[[0-9]+\\]" "argv[\\,\(+ 1 \\#\)]")
)

搜索字符串工作正常,但替換字符串給我錯誤“在替換文本中無效使用\\。我一直在嘗試添加或刪除一些\\但沒有成功。

任何的想法 ?

引用replace-regexp的幫助(粗體是我的):

交互式調用中,替換文本可能包含“\\”,

您沒有在您的defun中以交互方式使用它,因此出現錯誤消息。 來自同一幫助的另一個引用有助於解決您的問題:

This function is usually the wrong thing to use in a Lisp program.
What you probably want is a loop like this:
  (while (re-search-forward REGEXP nil t)
    (replace-match TO-STRING nil nil))
which will run faster and will not set the mark or print anything.

以及基於此的解決方案:

(defun argv-order ()
  (interactive)
  (let ((count 0))
    (while (re-search-forward "argv\\[[0-9]+\\]" nil t)
      (replace-match (format "argv[%d]" count) nil nil)
      (setq count (1+ count)))))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM