Created
April 12, 2013 02:55
-
-
Save codeforkjeff/5368956 to your computer and use it in GitHub Desktop.
string-match code fragment #4
see http://codefork.com/blog/index.php/2013/04/11/string-match-and-dealing-with-state/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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