views:

482

answers:

4

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?

+4  A: 

Does it need to be double-escaped?

i.e.

(replace-regexp-in-string "\/" "\\\\" path)
Peter Boughton
No, I have tried that already : C:/foo/bar becomes C:\\foo\\bar...
Peter
Have you tried \\\ too?
schnaader
yep :-) but that's a syntax error (the last quote is escaped than)
Peter
Another thought - this doesn't need to be a regex replace, since it's a straight substitution - does emacs/lisp offer a non-regex replace?
Peter Boughton
Double-escaped, ie. 4 consecutive backslashes *do* work.The reason you see 2 consecutive backslashes in the result is that they are escaped in the string. If you try to output the string again, it will look correct.
Lars Haugseth
You can also write it like this for better readability:(replace-regexp-in-string "/" (regexp-quote "\\") path)
Lars Haugseth
+1 (c Lars Haugseth)
Peter
A: 

Don't use emacs but I guess it supports some form of specifying unicode via \x

e.g. maybe this works

(replace-regexp-in-string "\x005c" "\x005f" path))

or

(replace-regexp-in-string "\u005c" "\u005f" path))
jitter
No, unicode is represented by \uXXXX or \u00XXXXXX.
Svante
um ok then switch to \u005c and \u005f? not?
jitter
+6  A: 

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.

Svante
A: 

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.

jlf
Not to rain on your parade but this answer was given up in the comments of the 2nd answer.
seth
Oops, missed that. Thank you.
jlf