[Rd] gsub + backslashes

Bill Dunlap bill at insightful.com
Mon Apr 24 17:32:48 CEST 2006


On Mon, 24 Apr 2006, Prof Brian Ripley wrote:

> On Mon, 24 Apr 2006, 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?
>
> Escape for R and escape for regexp:
>
> > gsub("\\\\", "x", "\\alpha")
> [1] "xalpha"

Also, unless fixed==TRUE, you need to double the backslash
in the replacement string (because \\<digit|U|L> has a special
meaning when fixed!=TRUE):

   > cat(gsub("/", "\\\\", "C:/Program Files/R"),"\n")
   C:\Program Files\R
   > cat(gsub("/", "\\", "C:/Program Files/R", fixed=T), "\n")
   C:\Program Files\R

----------------------------------------------------------------------------
Bill Dunlap
Insightful Corporation
bill at insightful dot com
360-428-8146

 "All statements in this message represent the opinions of the author and do
 not necessarily reflect Insightful Corporation policy or position."



More information about the R-devel mailing list