开发者

Regex Searching in Emacs

开发者 https://www.devze.com 2022-12-30 20:57 出处:网络
I\'m trying to write some Elisp code to format a bunch of legacy files. The idea is that if a file contains a section like \"<meta name=\\\"keywords\\\" content=\\\"\\\\(.*?\\\\)\\\" />\", then

I'm trying to write some Elisp code to format a bunch of legacy files.

The idea is that if a file contains a section like "<meta name=\"keywords\" content=\"\\(.*?\\)\" />", then I want to insert a section that contains existing keywords. If that section is not found, I开发者_高级运维 want to insert my own default keywords into the same section.

I've got the following function:

(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

When the function fails to find its target, it returns Search failed: "[regex here]" and prevents the rest of evaluation. Is there a way to have it return the default string, and ignore the error?


Use the extra options for re-search-forward and structure it more like

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


Also, consider using the nifty "rx" macro to write your regex; it'll be more readable.

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

精彩评论

暂无评论...
验证码 换一张
取 消