Posted By

bigfaceworm on 08/21/09


Tagged

replace String emacs LISP


Versions (?)

string-replace


 / 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

  1. ;; straight-forward solution doing just string manipulation
  2. ;; it's rather heavy handed
  3. (defun string-replace (from to string &optional re)
  4. "Replace all occurrences of FROM with TO in STRING.
  5. All arguments are strings.
  6. When optional fourth argument is non-nil, treat the from as a regular expression."
  7. (let ((pos 0)
  8. (res "")
  9. (from (if re from (regexp-quote from))))
  10. (while (< pos (length string))
  11. (if (setq beg (string-match from string pos))
  12. (progn
  13. (setq res (concat res
  14. (substring string pos (match-beginning 0))
  15. to))
  16. (setq pos (match-end 0)))
  17. (progn
  18. (setq res (concat res (substring string pos (length string))))
  19. (setq pos (length string)))))
  20. res))
  21.  
  22. ;; the more emacs way to do it is to use
  23. ;; string-replace - which has the drawback of not knowing *where*
  24. ;; the replacement was done, so if you apply this technique to strings
  25. ;; you can end up in an infinite loop
  26. ;; try: (string-replace "a" "aa" "a string contains a")
  27. ;; the "trick" is to put the string into a temporary buffer, like so:
  28.  
  29. (defun string-replace-2 (this withthat in)
  30. "replace THIS with WITHTHAT' in the string IN"
  31. (with-temp-buffer
  32. (insert in)
  33. (goto-char (point-min))
  34. (while (search-forward this nil t)
  35. (replace-match withthat nil t))
  36. (buffer-substring (point-min) (point-max))))

Report this snippet  

You need to login to post a comment.