正则表达式在Emacs中搜索

问题描述:

我正在尝试编写一些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]",防止评估的其余部分。有没有办法让它返回默认的字符串,并忽略错误?

使用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

而且,考虑使用漂亮的“RX”宏来写你的正则表达式;它会更具可读性。

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