/ Published in: Emacs Lisp
URL: http://stackoverflow.com/questions/41522/tips-for-learning-elisp/59589#59589
Two example solutions for the 'string-replace exercise listed here: http://stackoverflow.com/questions/41522/tips-for-learning-elisp/59589#59589
Expand |
Embed | Plain Text
;; straight-forward solution doing just string manipulation ;; it's rather heavy handed (defun string-replace (from to string &optional re) "Replace all occurrences of FROM with TO in STRING. All arguments are strings. When optional fourth argument is non-nil, treat the from as a regular expression." (let ((pos 0) (res "") (from (if re from (regexp-quote from)))) (while (< pos (length string)) (if (setq beg (string-match from string pos)) (progn (setq res (concat res (substring string pos (match-beginning 0)) to)) (setq pos (match-end 0))) (progn (setq res (concat res (substring string pos (length string)))) (setq pos (length string))))) res)) ;; the more emacs way to do it is to use ;; string-replace - which has the drawback of not knowing *where* ;; the replacement was done, so if you apply this technique to strings ;; you can end up in an infinite loop ;; try: (string-replace "a" "aa" "a string contains a") ;; the "trick" is to put the string into a temporary buffer, like so: (defun string-replace-2 (this withthat in) "replace THIS with WITHTHAT' in the string IN" (with-temp-buffer (insert in) (goto-char (point-min)) (while (search-forward this nil t) (replace-match withthat nil t)) (buffer-substring (point-min) (point-max))))
You need to login to post a comment.
