2010-05-14 138 views
1

我正在嘗試編寫一些Elisp代碼來格式化一堆遺留文件。正則表達式在Emacs中搜索

這個想法是,如果一個文件包含像"<meta name=\"keywords\" content=\"\\(.*?\\)\" />"這樣的部分,那麼我想插入一個包含現有關鍵字的部分。如果找不到該部分,我想將我自己的默認關鍵字插入到相同的部分。

我有以下功能:

(defun get-keywords() 
     (re-search-forward "<meta name=\"keywords\" content=\"\\(.*?\\)\" />") 
     (goto-char 0) ;The section I'm inserting will be at the beginning of the file 
     (or (march-string 1) 
      "Rubber duckies and cute ponies")) ;;or whatever the default keywords are 

當該功能無法找到它的目標,它返回Search failed: "[regex here]",防止評估的其餘部分。有沒有辦法讓它返回默認的字符串,並忽略錯誤?

回答

2

使用re-search-forward和結構額外的選項時,它更像

(if (re-search-forward "<meta name=\"keywords\" content=\"\\(.*?\\)\" />" nil t) 
    (match-string 1) 
    "Rubber duckies and cute ponies") 
+0

我落得這樣做'(保存衝程(如果(重新搜索了「[正則表達式這裏]」無T)(匹配字符串1)「橡膠duckies和可愛的小馬」))'。 感謝您將我指向「重新搜索前進」接受的NOERROR標誌。 – Inaimathi 2010-05-14 14:38:01

0

而且,考慮使用漂亮的「RX」宏來寫你的正則表達式;它會更具可讀性。

(rx "<meta name=\"keywords\" content=\"" 
    (group (minimal-match (zero-or-more nonl))) 
    "\" />")