Skip to content

Instantly share code, notes, and snippets.

@codeforkjeff
Created April 12, 2013 02:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeforkjeff/5368956 to your computer and use it in GitHub Desktop.
Save codeforkjeff/5368956 to your computer and use it in GitHub Desktop.
(defun my-replace (regex rep str &optional start)
"Replace matches of regex in str with the result of applying
rep function to the match.
This exists because of a quirk in replace-regexp-in-string:
because it calls the REP function in a while loop that uses
string-match and replace-match, the REP function can't use
string-match without messing up the match state in the loop.
If rep returns nil, an empty string is used as the
replacement."
(let ((found-pos (string-match regex str (or start 0))))
(if found-pos
(let* ((match (substring str found-pos (match-end 0)))
(replacement (if (stringp rep)
rep
(or (funcall rep match) ""))))
(my-replace regex
rep
(concat (substring str 0 found-pos)
replacement
(substring str (+ found-pos (length match))))
(+ found-pos (length replacement))))
;; else, we're done
str)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment