2017-08-21 replace-regexen-in-string

Recently, I had a need to do some replacements in a string. Basically, that meant repeatedly calling replace-regexp-in-string. I strongly disliked the idea of nesting these calls, so I set out to write a simple tool to help with that. Here is the result:

(defun replace-regexen-in-string (replacements string &optional fixedcase literal)
  "Call `replace-regexp-in-string' on STRING multiple times.
REPLACEMENTS is an alist of pairs (regex . replacement).
FIXEDCASE and LITERAL are passed to `replace-regexp-in-string'."
  (let ((result string))
	(mapc (lambda (replacement)
		(setq result
		  (replace-regexp-in-string (car replacement)
						(cdr replacement)
						result
						fixedcase
						literal)))
	  replacements)
	result))

It’s probably not the optimal/most beautiful way to do it. In particular, it is rather imperative and not very functional – I am pretty sure that it could be done more elegantly with reduce, or by a macro which would generate the recursive calls. Maybe some day I will write all three versions, and then measure their performance (I suspect my one should be rather a faster one). But it is optimal in terms of programmer time – I hacked it together in a few minutes, and much of that time was looking up replace-regexp-in-string syntax (and then checking whether the last two optional arguments work fine). Feel free to use it if you need to.

CategoryEnglish, CategoryBlog, CategoryEmacs