Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I would like to replace forward slaches to 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?

like image 588
Peter Avatar asked Jun 24 '09 10:06

Peter


3 Answers

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.

like image 167
Svante Avatar answered Oct 04 '22 03:10

Svante


Does it need to be double-escaped?

i.e.

(replace-regexp-in-string "\/" "\\\\" path)
like image 34
Peter Boughton Avatar answered Oct 04 '22 02:10

Peter Boughton


Try using the regexp-quote function, like so:

(replace-regexp-in-string "/" (regexp-quote "\\") "this/is//a/test")

regexp-quote's documentation reads

(regexp-quote string) Return a regexp string which matches exactly string and nothing else.

like image 34
jlf Avatar answered Oct 04 '22 03:10

jlf