Re: [Rd] gsub + backslashes

From: Simon Urbanek <simon.urbanek_at_r-project.org>
Date: Mon 24 Apr 2006 - 14:29:43 GMT

On Apr 24, 2006, at 10:23 AM, Torsten Hothorn wrote:

>
> Dear developeRs,
>
> I thought that backslashes can be escaped in the usual way (and I
> think I
> did this before) but I can't see why
>
> R> gsub("\\", "x", "\alpha")
> Error in gsub(pattern, replacement, x, ignore.case, extended, fixed,
> useBytes) :
> invalid regular expression '\'
>
> gives an error. Or am I just blind?
>

In REs you need to escape backslashes, so you need double-escaping: one for the R string representation and one for the RE:

 > gsub("\\\\", "x", "\\alpha")
[1] "xalpha"

For illustration purposes:

 > cat("\\\\")
\\
 > cat("\alpha")
lpha
 > cat("\\alpha")
\alpha

Cheers,
Simon



R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Tue Apr 25 00:41:33 2006

This archive was generated by hypermail 2.1.8 : Mon 24 Apr 2006 - 16:17:57 GMT