regexemacsstringlisp

How to replace forward slashes with backslashes in a string in Emacs Lisp?


I would like to replace forward slashes with backslashes in emacs lisp. If I use this :

(replace-regexp-in-string "\/" "\\" path))

I get an error.

(error "Invalid use of `\\' in replacement text")

So how to represent the backslash in the second regexp?


Solution

  • What you are seeing in "C:\\foo\\bar" is the textual representation of the string "C:\foo\bar", with escaped backslashes for further processing.

    For example, if you make a string of length 1 with the backslash character:

    (make-string 1 ?\\)
    

    you get the following response (e.g. in the minibuffer, when you evaluate the above with C-x C-e):

    "\\"
    

    Another way to get what you want is to switch the "literal" flag on:

    (replace-regexp-in-string "/" "\\" path t t)
    

    By the way, you don't need to escape the slash.