Elisp: Replace String or Regex in String

By Xah Lee. Date: . Last updated: .

String Replace

string-replace

(string-replace FROM-STRING TO-STRING IN-STRING)

new in Emacs 28 (date 2022)

String Replace with Regex

replace-regexp-in-string

(replace-regexp-in-string REGEXP REP STRING &optional FIXEDCASE LITERAL SUBEXP START)

  • Replace REGEXP pattern by REP in STRING.
  • All matches are replaced.
  • Return a new string.

REP can be a string or a function.

If REP is a string:

  • \N → nth capture. It is empty string if capture didn't match.
  • \& → the original matched text.
  • \\ → means one backslash.

If REP is a function:

  • it is called for each match.
  • It is feed one arg, the matched part.
  • The return value must be string, is used as replacement
  • When REP is called, the Elisp: Match Data (Regex Result) is updated.
  • FIXEDCASE → use REP string as is, no smart letter-case change.
  • LITERAL → no special interpretation of backslash in REP.
  • SUBEXP → value is a positive integer, it means replace only that part of captured group specified in REGEXP.
  • START is a index, means start replacements at that point. Ignore all chars before, nor return that in result.
;; simple example of replace-regexp-in-string
;; replacing html div element to p
(replace-regexp-in-string "</*div>" "<p>" "<div>something</div>")
;; "<p>something<p>"
;; example of replace-regexp-in-string
;; fixed case example vs not

;; normal. smart case replacement
(replace-regexp-in-string "alice" "queen" "ALICE, Alice, alice")
;; "QUEEN, Queen, queen"

;; fixed case
(replace-regexp-in-string "alice" "queen" "ALICE, Alice, alice" t)
;; "queen, queen, queen"
;; example of using replace-regexp-in-string
;; with function as replacement string

(let ((xx "screenshot_2025-02-18_134637.png"))

  ;; we want to change the 134636 for hhmmss to a hexadecimal, with min of 5 digits, padding with 0

  (replace-regexp-in-string
   "\\([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\\)_\\([0-9]\\{6\\}\\)"
   (lambda (x)
     (concat
      (match-string 1 x) "_" (format "%05x" (string-to-number (match-string 2 x)))))
   xx t))

;; "screenshot_2025-02-18_20ded.png"
;; example of using replace-regexp-in-string

;; normal
(replace-regexp-in-string "\\([0-9]+\\) \\([0-9]+\\)" "x" "70 82 06 96" t t )
;; "x x"

;; replacing just first captured group
(replace-regexp-in-string "\\([0-9]+\\) \\([0-9]+\\)" "x" "70 82 06 96" t t 1)
;; "x 82 x 96"

Emacs Lisp, String