[R] escaping backslash in a string

Dan Lipsitt danlipsitt at gmail.com
Mon Nov 29 20:12:33 CET 2004


I have it working now, I think. Since it's going into a regular
expression, I have to escape each of the escape characters, resulting
in four backslashes altogether:

> sub("[.]", "x", "a.b")
[1] "axb"
> sub("[.]", "\.", "a.b")
[1] "a.b"
> sub("[.]", "\\.", "a.b")
[1] "a.b"
> sub("[.]", "\\\.", "a.b")
[1] "a.b"
> sub("[.]", "\\\\.", "a.b")
[1] "a\\.b"
> cat(sub("[.]", "\\\\.", "a.b"))
a\.b>

or

> cat(sub("\\.", "\\\\.", "a.b"))
a\.b> 

Dan




More information about the R-help mailing list