5

I've defined a function that is supposed to iterate over an alist, and use the CAR and CDR of each element in the list to populate the regexp in re-search-forward and the replacement string in replace-match, respectively. Here is what I have:

(defun search-and-replace ()
  (let ((alist '(("regexp" "replacement-str")
                 ...)))
    (dolist (search-pair alist)
      (point-min)
      (while (re-search-forward (car search-pair) nil t)
        (replace-match (cdr search-pair))))))

This returns an error: Wrong type argument: stringp, ("replacement-str"). What am I missing?

Edit:

Thanks for the help. Here's what I ended up with:

(defun search-and-replace (alist)
  (save-excursion
    (goto-char (point-min))
    (dolist (search-pair alist)
      (while (re-search-forward (car search-pair) nil t)
        (replace-match (cdr search-pair)))
      (goto-char (point-min))))

Where each item in ALIST is a cons cell of ("regexp" . "replacement-string").

  • 1
    @rjww I don't think YoungFrog was talking down to you, I see only helpful comments. Perhaps you read some sarcasm into it, but I don't think any was intended. – npostavs Jan 14 '17 at 6:07
  • @YoungFrog I must have misread the tone, sorry everyone. – rjww Jan 14 '17 at 6:48
  • @rjww I guess I missed some now-deleted comments, but I confirm what npostavs said. I like reading comments that are short and go straight to the point, so I try to write them that way too ; sorry if it sounded harsh. Nothing personal of course. – YoungFrog Jan 15 '17 at 11:26
  • @YoungFrog No it was my fault. Thanks very much for your help, I appreciate it. – rjww Jan 15 '17 at 12:26
5

You want (cadr search-pair), not (cdr search-pair).

Either that or use an alist whose entries are dotted pairs, with the cdrs being your replacement strings.

The error message tells you that a string was expected and instead the list ("replacement-str") was passed.

  • Thanks, that did it. I actually meant to include them as dotted pairs, but conveniently messed it up in both the code and the example above. – rjww Jan 14 '17 at 3:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.