tags:

views:

66

answers:

2

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?

+2  A: 

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")
scottfrazer
I ended up doing `(save-excursion (if (re-search-forward "[regex here]" nil t) (match-string 1) "Rubber duckies and cute ponies"))`.Thanks for pointing me to the NOERROR flag that `re-search-forward` accepts.
Inaimathi
A: 

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)))
    "\" />")
offby1